您不應該從非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