如何在任务运行时完全停止任务?
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>
}
如果我想在第二件事处理期间停止任务,我点击一个按钮2然后任务将停止处理
如何从button2_Click
取消或结束任务?
答案 0 :(得分:5)
// 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