using System;
using System.ComponentModel;
using System.Threading;
namespace pc.BackgroundworkerExmaple
{
class Program
{
static void Main(string[] args)
{
char selection;
bool showProgress = false;
var bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
bgw.WorkerSupportsCancellation = true;
bgw.DoWork += (s, e) =>
{
var worker = s as BackgroundWorker;
for (int i = 0; i
< 10; i++)
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
else
{
Thread.Sleep(1000);
worker.ReportProgress(i
* 10);
}
};
bgw.RunWorkerCompleted += (s, e)
=>
{
var worker = s as BackgroundWorker;
if (e.Cancelled)
Console.WriteLine("Canceled");
else if (e.Error != null)
Console.WriteLine($"error: {e.Error.Message}");
else
Console.WriteLine("Background task complete");
};
bgw.ProgressChanged += (s, e) =>
{
if(showProgress)
Console.WriteLine($"{e.ProgressPercentage}%");
showProgress = false;
};
do
{
if (bgw.IsBusy)
Console.Write("2) Progress\n3) Cancel");
else
Console.Write("1) Start\n");
Console.WriteLine("0) Exit");
selection = Console.ReadKey().KeyChar;
switch (selection)
{
case '1':
if (!bgw.IsBusy)
bgw.RunWorkerAsync();
else
Console.WriteLine("already running");
break;
case '2':
if (bgw.IsBusy)
showProgress = true;
else
Console.WriteLine("not running");
break;
case '3':
if(bgw.IsBusy)
bgw.CancelAsync();
else
Console.WriteLine("not running");
break;
}
} while (selection != '0');
}
}
}