Pattern - Console
Creating
Open Visual Studio 2022 as Administrator.
Create a New Project, language C#, platform Windows, project type Console.
Find "Console App" and press Next
Change the Project Name to "Console_Threading_BW".
Check / change the Location if necessary.
Press Next.
Check / Change the Framework to .NET 6.0.
Press Create.
This will create a solution that contains one project
SS
Add the following code to the Program.cs file
class Program
{
static void Main(string[] args)
{
System.ComponentModel.BackgroundWorker _workerThread1 = new System.ComponentModel.BackgroundWorker();
_workerThread1.DoWork += method_worker_DoWork;
_workerThread1.WorkerReportsProgress = true;
_workerThread1.ProgressChanged += method_worker_ProgressChanged;
_workerThread1.RunWorkerCompleted += method_worker_RunWorkerCompleted;
_workerThread1.WorkerSupportsCancellation = true;
System.Console.WriteLine("Background Worker has started (press any key to cancel/exit)");
_workerThread1.RunWorkerAsync();
Console.ReadKey(true);
if (_workerThread1.IsBusy)
{
System.Console.WriteLine("Background Worker has been interrupted");
_workerThread1.CancelAsync();
var sw = System.Diagnostics.Stopwatch.StartNew();
while (_workerThread1.IsBusy && sw.ElapsedMilliseconds < 5000)
{
System.Threading.Thread.Sleep(1);
}
}
}
static void method_worker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
System.Console.WriteLine("Worker progress: {0:d}%", e.ProgressPercentage);
}
static void method_worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
System.ComponentModel.BackgroundWorker _workerThread2 = sender as System.ComponentModel.BackgroundWorker;
System.Console.WriteLine("Background Worker is busy");
e.Result = 0;
for (int i = 1; i < 11; ++i)
{
for (int j = 0; !_workerThread2.CancellationPending && j < 10; ++jj)
{
System.Threading.Thread.Sleep(100);
}
if (_workerThread2.CancellationPending)
{
break;
}
_workerThread2.ReportProgress((int)((100.0 * i) / 10));
e.Result = i;
}
e.Cancel = _workerThread2.CancellationPending;
}
static void method_worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
System.Console.WriteLine("Background Worker has been cancelled");
return;
}
System.Console.WriteLine("Background Worker has finished");
}
}
Running
Build the solution and press F5.
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext