前言:
①取消task任务之CancellationTokenSource的用法;
②task的线程管控方法Task..Wait(time),Task.WaitAll(), Task.WaitAny(),task.ContinueWith.
1.声明参数
代码语言:javascript复制 CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
ManualResetEvent resetEvent = new ManualResetEvent(true);
2.定义Task
代码语言:javascript复制Task task = new Task(async () => {
while (true) {
if (token.IsCancellationRequested) {
return;
}
// 初始化为true时执行WaitOne不阻塞
resetEvent.WaitOne();
// Doing something.......
// 模拟等待100ms
await Task.Delay(100);
}
}, token);
task.Start();
3.暂停Task
代码语言:javascript复制resetEvent.Reset();
4.继续Task
代码语言:javascript复制resetEvent.Set();
5.取消Task
代码语言:javascript复制tokenSource.Cancel();
实例:
代码语言:javascript复制 #region TASK用法举例
static void TasKTest()
{
//带返回值的task
Task<String> mytask = Task.Run(async () =>
{
await Task.Delay(5000);
return "老铁666";
}, cancellationToken.Token);
//cancellationToken.Cancel();
while (!mytask.Wait(100)) //在指定时间执行完成就返回true
{
Console.Write(".");
}
Console.WriteLine(mytask.Result);//task任务取消,所以获取task.Result会报错
Task taskFactory = Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
Console.WriteLine("perfect!");
});
Console.WriteLine(taskFactory.Status);
taskFactory.Wait();//taskFactory任务完成才往下执行
Task.WaitAll(mytask, taskFactory);//所有任务完成再往下执行
Task.WaitAny(mytask, taskFactory);//任一任务完成就往下执行
Console.WriteLine(taskFactory.Status);
Task taskTest = taskFactory.ContinueWith(DoOnSecond);//ContinueWith用法举例
}
static void DoOnSecond(Task t)
{
Console.WriteLine("task {0} finished", t.Id);
Console.WriteLine("this task id {0}", Task.CurrentId);
Console.WriteLine("do some cleanup");
}
#endregion