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
?
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.
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.
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.
// 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With