BackgroundWorker 组件-LMLPHP

代码:

 static void Main(string[] args)
{
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += Worker_doWork;
bw.ProgressChanged += Worker_ProcessChanged;
bw.RunWorkerCompleted += Worker_Completed;
bw.RunWorkerAsync();
Console.WriteLine("Press C to Cancel");
do
{
if (Console.ReadKey(true).KeyChar == 'C')
{
bw.CancelAsync();
}
}
while (bw.IsBusy);
} static void Worker_doWork(object sender, DoWorkEventArgs e)
{
Console.WriteLine("当前线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
BackgroundWorker bw = (BackgroundWorker)sender;
for (int i = ; i <= ; i++)
{
if (bw.CancellationPending == true)
{
e.Cancel = true;
return;
}
if (i % == )
{
bw.ReportProgress(i);
}
Thread.Sleep(TimeSpan.FromSeconds(0.1));
}
e.Result = ;
} static void Worker_ProcessChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("%{0} is Completed. process thread pool thread id {1}", e.ProgressPercentage, Thread.CurrentThread.ManagedThreadId);
}
static void Worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("完成的线程ID:{0}",Thread.CurrentThread.ManagedThreadId);
if (e.Error != null)
{
Console.WriteLine(e.Error.Message);
}
else if (e.Cancelled)
{
Console.WriteLine("Operation has been canceled");
}
else
{
Console.WriteLine("The Answer is {0}:",e.Result);
}
}

运行结果:

BackgroundWorker 组件-LMLPHP

05-02 10:00