class Program
{
static BackgroundWorker bw;
static void Main(string[] args)
{
bw = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
bw.DoWork += Bw_DoWork;
bw.ProgressChanged += Bw_ProgressChanged;
bw.RunWorkerCompleted += Bw_RunWorkerCompleted;
//开始工作(新线程)
bw.RunWorkerAsync("Hello");
Console.ReadLine();
if (bw.IsBusy)
bw.CancelAsync();
Console.ReadLine();
}
//工作进度完成事件
private static void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
Console.WriteLine("You canclled!");
}
else if (e.Error != null)
{
Console.WriteLine($"Error:{e.Error}");
}
else
Console.WriteLine($"Completed-{e.Result}");
}
//进度改变后事件
private static void Bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine($"Reached {e.ProgressPercentage}%");
}
private static void Bw_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
Console.WriteLine("Press Enter in the next 5 seconds to cancel");
for (int i = 0; i <= 100; i += 20)
{
//若是取消了
if (bw.CancellationPending)
{
e.Cancel = true;
return;
}
//报告进度变化,引发进度改变事件
bw.ReportProgress(i);
Thread.Sleep(1000);
}
e.Result = 123;
}
}
}