My solution is:
1. The C#.NET tasks cancelation mechanism will work regardless of whether it is an async-await or regular synchronous button click event handler;
2. Please make sure that you are using CancellationTokenSource object in your C# code;
3. Please make sure that you are performing a check if CancellationTokenSource.IsCancellationRequested property value is "true" prior to each driver installation phase within the asynchronous task spawned;
4. Please make sure that you've implemented a separate handler for cancelation button click and invoke CancellationTokenSource.Cancel() method;
Here's how: (e.g. the following code below implements a System.Windows.Form windows-based application having two buttons. The first button normally launches adding driver task. In this case it spawns a task that displays a message box repeatedly in the ethernal loop, simulation the driver installation work. To spawn the task all you need is to click on Add Driver... button. To cancel the so-called "driver installation", you have to toggle cancel task button and the message boxes will no longer be displayed indicating that the specific task has been cancelled:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
static public CancellationTokenSource
tokenAddDriverSource = new CancellationTokenSource();
public Form1()
{
InitializeComponent();
}
private async void BtnAddDriver_Click(object sender, EventArgs e)
{
try {
try
{
await Task.Factory.StartNew(() =>
{
bool isCanceled = false;
while (isCanceled == false)
{
if (tokenAddDriverSource.IsCancellationRequested)
isCanceled = true;
MessageBox.Show("Fire Do Action in protect to get the driver details after adding the driver in protect");
if (tokenAddDriverSource.IsCancellationRequested)
isCanceled = true;
if (tokenAddDriverSource.IsCancellationRequested)
isCanceled = true;
}
}, tokenAddDriverSource.Token);
}
catch (Exception ex)
{
}
finally
{
}
}
catch (Exception ex)
{
}
finally
{
}
}
private void CancelTask_Click(object sender, EventArgs e)
{
tokenAddDriverSource.Cancel();
}
}}
And, one more thing: to perform task cancelation properly, you would better, divide the entire driver installation process into several phases and execute the following code prior to driver installation each phase:
if (tokenAddDriverSource.IsCancellationRequested)
isCanceled = true;
That's all :)