Stop Task when task run

18,547
// 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
Share:
18,547
James Wang
Author by

James Wang

Updated on June 16, 2022

Comments

  • James Wang
    James Wang almost 2 years

    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?

  • James Wang
    James Wang almost 8 years
    i get a error in CancellationToken token = null; (Cannot convert null to 'System.Threading.CancellationToken' because it is a non-nullable value)
  • Jalali Shakib
    Jalali Shakib almost 7 years
    I think you must use source.Token when instantiating Task.