I want to cancel a running task (when the users presses the escape key). when i click on "escape" key Form_KeyDown run but doesn't cancel task!
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token=new CancellationToken();
private async void Search_Button_ClickAsync(object sender, EventArgs e)
{
token = tokenSource.Token;
await (Task.Factory.StartNew(() =>
{
//...my program
},
token));
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
tokenSource.Cancel();
}
}
You are doing all ok except the fact that you need to stop your code from running inside your method. By passing cancellation token to Task.Factory.StartNew you are not aborting the task. Let me quote
Stephen Toub
:You need to manually check if your token was cancelled and throw operation canceled exception, something along these lines: