【发布时间】:2011-07-30 21:57:59
【问题描述】:
我正在制作一个程序,从 txt 文件导入电子邮件并向他们发送消息,但我遇到了一个问题,目前我正在使用一个线程来发送邮件方法以防止程序停止响应,确切的问题标题是:
处理了无效的操作异常
>>> 跨线程操作无效:
控件“richTextBox1”从创建它的线程以外的线程访问。
这里是代码
int success = 0;
int failed = 0;
int total = 0;
bool IsRunning;
List<string> list = new List<string>();
private void addmails()
{
string path = textBox2.Text;
foreach (string line in File.ReadAllLines(path))
{
list.Add(line);
}
IsRunning = true;
}
private void sendmails(object sender, DoWorkEventArgs e)
{
if (IsRunning == true)
{
if (checkBox1.Checked != true)
{
SmtpClient client = new SmtpClient(comboBox1.Text);
client.Credentials = new NetworkCredential(textBox6.Text, textBox7.Text);
MailMessage message = new MailMessage();
message.From = new MailAddress(textBox3.Text, textBox1.Text);
message.Subject = textBox4.Text;
//message.Body = richTextBox1.Text;
if (textBox5.Text != "")
{
message.Attachments.Add(new Attachment(textBox5.Text));
}
foreach (string eachmail in list)
{
if (IsRunning == true)
{
try
{
message.To.Add(eachmail);
client.Send(message);
listBox1.Items.Add("Successfully sent the message to : " + eachmail);
success++;
}
catch
{
listBox1.Items.Add("Failed to send the message to : " + eachmail);
failed++;
}
message.To.Clear();
total++;
Thread.Sleep(15);
label18.Text = total.ToString();
label19.Text = success.ToString();
label21.Text = failed.ToString();
}
else
{
break;
}
}
IsRunning = false;
button3.Text = "Send";
}
}
}
private void button3_Click(object sender, EventArgs e)
{
if (button3.Text == "Send")
{
tabControl1.SelectedTab = tabPage3;
button3.Text = "Stop";
addmails();
// IsRunning = true;
Thread t2 = new Thread(sendmails); // when using that thread i get a cross threading error
t2.Start();
}
else
{
IsRunning = false;
button3.Text = "Send";
MessageBox.Show("Sending Mails Operation has been terminated","Abort",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
【问题讨论】:
-
请尽量避免问题描述仅出现在标题中。您应该发布实际的异常以及它发生的位置。
-
正如@Lasse V. Karlsen 所说,您看到的实际异常是什么?
-
确切的问题标题是:处理了无效的操作异常>>> 跨线程操作无效:控件'richTextBox1'从创建它的线程以外的线程访问。
标签: c# winforms multithreading