写入富文本框。

时间:2011-07-28 19:18:04

标签: c#

所以这是我的问题。我的电子邮件应用程序发送电子邮件,在发送结束时,我将邮件的状态写入富文本框。这是问题。假设我发送了10封电子邮件,则每次迭代都不会更新richtext框。当发送所有10封电子邮件时,将使用已发送的消息更新该框。似乎应用程序在通过四个循环时被冻结。

for (int count = 0; count < numEmailToSend; count++)
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                if (typeSelectedItem == "text/html") { message.IsBodyHtml = true; }
                if (typeSelectedItem == "text/plain") { message.IsBodyHtml = false; }

                message.To.Add(emailAddress);

                if (txtCC.Text != "")
                {message.CC.Add(txtCC.Text);}
                if (txtBCC.Text != "")
                {message.Bcc.Add(txtBCC.Text);}

                message.Subject = subject;
                message.From = new System.Net.Mail.MailAddress(emailSender);
                message.Body = body;
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(server);
                rtbStatus.Text = rtbStatus.Text + "Starting to Send Message\r\n";
                Thread.Sleep(avgDelay * 1000);
                //smtp.Send(message);
                smtp.SendAsync(message,1);
                rtbStatus.Text = rtbStatus.Text + "Message Sent\r\n";
            }

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

你是对的。
当您的代码在UI线程中运行时,UI无法更新。

您应该在后台线程上运行代码 您可以使用BackgroundWorker组件来简化此操作。

请注意,您无法从后台线程与UI进行交互;要更新文本框,您应该使用更新文本的匿名方法调用BeginInvoke,或使用BackgroundWorker的内置进度报告功能。

相关问题