前言:
①取消task任务之CancellationTokenSource的用法;
②task的线程管控方法Task..Wait(time),Task.WaitAll(), Task.WaitAny(),task.ContinueWith.
1.声明参数
CancellationTokenSource tokenSource = new CancellationTokenSource();CancellationToken token = tokenSource.Token;ManualResetEvent resetEvent = new ManualResetEvent(true);
2.定义Task
Task task = new Task(async () => {while (true) { if (token.IsCancellationRequested) {return;}// 初始化为true时执行WaitOne不阻塞resetEvent.WaitOne();// Doing something.......// 模拟等待100msawait Task.Delay(100);}}, token);task.Start();
3.暂停Task
resetEvent.Reset();
4.继续Task
resetEvent.Set();
5.取消Task
tokenSource.Cancel();
实例:
#region TASK用法举例static void TasKTest(){//带返回值的taskTask<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
进技术交流群的,加小编微信zls20210502,切记备注:进群!
历史经典文章回顾:以下都是以往阅读量好,比较经典的篇章!(下面是超链接,点击就可以过去)
C# 看懂这100+行代码,你就真正入门了(经典)
C# WPF项目实战(经典)
C# NOPI 项目实战(经典)(可下载项目源码)WPF【框架学习】MVVM初探(经典)
C# action,delegate,func的用法和区别
C#接口的作用(经典)
C# 三种方式实现Socket数据接收(经典)