任务运行时停止任务 [英] Stop Task when task run

查看:267
本文介绍了任务运行时停止任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>
}

如果说我想在第二件事情期间停止任务, a button2然后任务将停止进程

If say i want to stop task during 2nd thing is processing, and i click a button2 then the task will stop process

如何从 button2_Click 取消或结束任务?

How do I cancel or end the task from button2_Click?

推荐答案

// 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

这篇关于任务运行时停止任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆