需要实现这样一个功能。
WInForm上设计了一个RichTextBox控件,后台每一条处理,都要在其中输出Log,处理一条,输出一条。
想到用多线程来实现,在线程的执行方法中,每处理一条数据,直接操作RichTextBox来输出Log,
但是报了Cross-thread operation not valid异常,原来RichTextBox不是该线程里创建的对象,不能操作。
查了一些资料,通过线程内调用委托的方式,解决了问题。(用BackgroundWorker应该也能实现)
大致的实现思路如下:
private void btnOK_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(Action));
thread.IsBackground = true;
thread.Start();
}
private void Action()
{
//定义了一个委托,并在此处创建该委托的实力
ReportLogDelegate reportAsync = new ReportLogDelegate(ReportLog);
for(int i = 0; i < files.count; i++)
{
Thread.Sleep(100);
if(this.richbox.InvokeRequired)
{
object[] parameters = {files[i]};
this.Invoke(reportAsync , parameters);
}
}
}
private void ReportLog(string str)
{
this.richbox.Text += (str + "\r\n");
}