Task实现暂停、继续、结束。
看到这个,有些童鞋可能会想到自动化设备上的“停止”,“开始”按钮。
勇哥要说的是,Task的暂停继续只是对于task的调度流程来说的,至于task内部跑的轴的运动逻辑来说,你还得有另外的办法让它同步暂停继续。
所以整机控制功能并不是靠线程的挂起与继续就那么容易实现的。
代码:
几点说明。
你可以在return那里下断点,程序最后会取消task的执行,就断在这里了。
因为这个是异步的代码,所以你只能这样检测取消功能了。
另外,对于WaitOne()之后的set和Reset,请记住口诀: Reset暂停,Set启动
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication19
{
class Program
{
static void Main(string[] args)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
ManualResetEvent resetEvent = new ManualResetEvent(true);
Task task = new Task(async () =>
{
//输出i
int i = 0;
while (true)
{
if (token.IsCancellationRequested)
{
return;
}
resetEvent.WaitOne();
//do something
Console.WriteLine(i++);
await Task.Delay(100);
}
}, token);
task.Start();
//2秒后暂停
Thread.Sleep(2000);
resetEvent.Reset();
Console.WriteLine("Reset");
//2秒后启动
Thread.Sleep(2000);
resetEvent.Set();
Console.WriteLine("Set");
//2秒后暂停
Thread.Sleep(2000);
resetEvent.Reset();
Console.WriteLine("Reset");
tokenSource.Cancel();
Console.ReadKey();
}
}
}
---------------------
作者:hackpig
来源:www.skcircle.com
版权声明:本文为博主原创文章,转载请附上博文链接!


少有人走的路


















