更新时间:2023-12-04 09:12:10
// Define the cancellation token source & token as global objects
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = null;
//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