I am building a C# / Windows Forms application.
Inside the click event handlers for various buttons on a form, I initialize and fire off different tasks. However, for certain button clicks, I want to cancel out any tasks that are still running that were started by certain other click event handlers.
Below is my code. The second version is my attempt so far at getting the second method to cancel out a running task started by the first method, however it does not work yet. How can I cancel the running Task?
Example Code (no cancellationtokens added yet):
private void btnFrontDoorCycle_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
// Do function 1
// Do function 2
// etc
});
}
private void btnFrontDoorClose_Click(object sender, EventArgs e)
{
// If task started in btnFrontDoorCycle_Click is running, cancel it here
Task.Factory.StartNew(() =>
{
// Do function 5
// Do function 6
// etc
});
}
Example Code (my non-functioning attempt at adding in cancellationtokens):
private CancellationTokenSource cancellationTokenSource;
private void btnFrontDoorCycle_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
// Do function 1
// Do function 2
// etc
}, cancellationToken);
}
private void btnFrontDoorClose_Click(object sender, EventArgs e)
{
// If task started in btnFrontDoorCycle_Click is running, cancel it here
if (this.cancellationTokenSource != null)
{
this.cancellationTokenSource.Cancel();
}
this.cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = this.cancellationTokenSource.Token;
Task.Factory.StartNew(() =>
{
// Do function 5
// Do function 6
// etc
});
}