BackgroundWorker
有關如何使用 BackgroundWorker
物件在後臺執行緒中執行時間密集型操作的簡單示例,請參見下文。
你需要:
- 定義一個執行時間密集型工作的 worker 方法,並從
BackgroundWorker
的DoWork
事件的事件處理程式中呼叫它。 - 用
RunWorkerAsync
開始執行。附加到DoWork
的 worker 方法所需的任何引數都可以通過DoWorkEventArgs
引數傳遞給RunWorkerAsync
。
除了 DoWork
事件之外,BackgroundWorker
類還定義了兩個應該用於與使用者介面互動的事件。這些是可選的。
- 當
DoWork
處理程式完成時會觸發RunWorkerCompleted
事件。 - 呼叫
ReportProgress
方法時會觸發ProgressChanged
事件。
public void ProcessDataAsync()
{
// Start the time intensive method
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += BwDoWork;
bw.RunWorkerCompleted += BwRunWorkerCompleted;
bw.RunWorkerAsync(@"PATH_TO_SOME_FILE");
// Control returns here before TimeintensiveMethod returns
Console.WriteLine("You can read this while TimeintensiveMethod is still running.");
}
// Method that will be called after BwDoWork exits
private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// we can access possible return values of our Method via the Parameter e
Console.WriteLine("Count: " + e.Result);
}
// execution of our time intensive Method
private void BwDoWork(object sender, DoWorkEventArgs e)
{
e.Result = TimeintensiveMethod(e.Argument);
}
private int TimeintensiveMethod(object file)
{
Console.WriteLine("Start TimeintensiveMethod.");
// Do some time intensive calculations...
using (StreamReader reader = new StreamReader(file.ToString()))
{
string s = reader.ReadToEnd();
for (int i = 0; i < 10000; i++)
s.GetHashCode();
}
Console.WriteLine("End TimeintensiveMethod.");
// return something as a "result"
return new Random().Next(100);
}