我已經編寫了一個示例控制檯應用程序,以使用在此處發佈的其中一個示例在Stackoverflow中測試backgroundworker。我有一個背景工作,它以主要方法開始,但在操作過程中結束,如果我按下回車鍵,因爲我在主要方法中寫了一個console.readkey。但我希望它能夠等到背景工作者完成作業然後退出應用程序。這是我的代碼。如何等待BackgroundWorker完成,然後退出控制檯應用程序
class Program
{
private static BackgroundWorker worker = new BackgroundWorker();
private event EventHandler BackgroundWorkFinished;
static void Main(string[] args)
{
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.ProgressChanged += worker_ProgressChanged;
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
Console.WriteLine("Starting Application...");
worker.RunWorkerAsync();
Console.ReadKey();
}
static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine(e.ProgressPercentage.ToString());
}
static void worker_DoWork(object sender, DoWorkEventArgs e)
{
Console.WriteLine("Starting to do some work now...");
int i;
for (i = 1; i < 10; i++)
{
Thread.Sleep(1000);
worker.ReportProgress(Convert.ToInt32((100.0 * i)/10));
}
e.Result = i;
}
static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Value Of i = " + e.Result.ToString());
Console.WriteLine("Done now...");
}
}
爲什麼你然後運行後臺進程異步?這似乎是你想要它同步運行... – 2010-09-22 10:30:13
如何同步運行它..? – 2010-09-22 11:04:15
可能重複的[如何等待BackgroundWorker取消?](http://stackoverflow.com/questions/123661/how-to-wait-for-a-backgroundworker-to-cancel) – 2014-03-01 10:20:28