8

How can i totally stop a task when task running?

private async void button1_Click(object sender, EventArgs e)
{
  await Backup(file);
}

public async Task Backup(string File)
{
   await Task.Run(() =>
     {
       1)do something here

       2)do something here

       3)do something here

      });
}
private async void button2_Click(object sender, EventArgs e)
{
  <stop backup>
}

If say i want to stop task during 2nd thing is processing, and i click a button2 then the task will stop process

How do I cancel or end the task from button2_Click?

1

1 Answer 1

17
// Define the cancellation token source & token as global objects 
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token;

//when button is clicked, call method to run task & include the cancellation token 

private async void button1_Click(object sender, EventArgs e)
{
    token = source.Token;
    await Backup(file, token);
}

public async Task Backup(string File, CancellationToken token)
{
    Task t1 = Task.Run(()  =>
    {
        //do something here
    }, 
    token);
} 

//cancel button click event handler 
private async void cancelButton_Click(object sender, EventArgs e)
{
    if(source != null) 
    {
        source.Cancel();
    } 
}

//tasks
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx 

//CancellationToken
https://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken(v=vs.110).aspx
2
  • i get a error in CancellationToken token = null; (Cannot convert null to 'System.Threading.CancellationToken' because it is a non-nullable value)
    – James Wang
    May 1, 2016 at 9:03
  • I think you must use source.Token when instantiating Task. May 28, 2017 at 8:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.