任务运行时停止任务

时间:2016-04-28 10:15:24

标签: c# .net multithreading c#-4.0 async-await

如何在任务运行时完全停止任务?

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取消或结束任务?

1 个答案:

答案 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