Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Task when task run [duplicate]

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?

like image 804
James Wang Avatar asked Apr 28 '16 10:04

James Wang


People also ask

How do I stop a task from running?

Open Start, do a search for Task Manager and click the result. Use the Ctrl + Shift + Esc keyboard shortcut. Use the Ctrl + Alt + Del keyboard shortcut and click on Task Manager. Use the Windows key + X keyboard shortcut to open the power-user menu and click on Task Manager.

How do I cancel async tasks?

You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.

How do I cancel a CancellationToken?

A CancellationToken can only be created by creating a new instance of CancellationTokenSource . CancellationToken is immutable and must be canceled by calling CancellationTokenSource. cancel() on the CancellationTokenSource that creates it. It can only be canceled once.


1 Answers

// 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
like image 129
Themba Avatar answered Sep 17 '22 15:09

Themba