您不应该从非UI线程访问UI元素。运行ReportProgress
,它将与UI线程同步。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
foreach (System.Diagnostics.EventLogEntry entry in eventLog1.Entries)
{
var newEntry = entry.EntryType + " - " + entry.TimeWritten + " - " + entry.Source;
backgroundWorker1.ReportProgress(0, newEntry);
}
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var newEntry = (string)e.UserState;
listBox1.Items.Add(newEntry);
}
确保启用WorkerReportsProgress
。
backgroundWorker1.WorkerReportsProgress = true;
和订阅ProgressChanged
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
另一种方法是调用Control.Invoke
内
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
foreach (System.Diagnostics.EventLogEntry entry in eventLog1.Entries)
{
var newEntry = entry.EntryType.ToString() + " - " + entry.TimeWritten + " - " + entry.Source;
Action action =() => listBox1.Items.Add(newEntry);
Invoke(action);
}
}
但是这种方法不需要BackgroundWorker
为整点是用ProgressChanged
和RunWorkerCompleted
事件处理程序,它们与UI线程同步。
就以这个答案一看:http://stackoverflow.com/questions/1136399/how-to -update-文本框上的图形用户界面,从-另一个线程在C# – Klinger 2011-06-12 07:25:15