前言:
①取消task任务之CancellationTokenSource的用法;
②task的线程管控方法Task..Wait(time),Task.WaitAll, Task.WaitAny,task.ContinueWith.
1.声明参数
CancellationTokenSource tokenSource = newCancellationTokenSource;
CancellationToken token = tokenSource.Token;
ManualResetEvent resetEvent = newManualResetEvent( true);
2.定义Task
Task task = newTask( async=> {
while( true) {
if(token.IsCancellationRequested) {
return;
}
// 初始化为true时执行WaitOne不阻塞
resetEvent.WaitOne;
// Doing something.......// 模拟等待100msawaitTask.Delay( 100); }
}, token);
task.Start;
3.暂停Task
resetEvent.Reset;
4.继续Task
resetEvent.Set;
5.取消Task
tokenSource.Cancel;
实例:
# regionTASK用法举例 staticvoidTasKTest( ) {//带返回值的taskTask<String> mytask = Task.Run( async=> {awaitTask.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用法举例}staticvoidDoOnSecond( Task t) {Console.WriteLine( "task {0} finished", t.Id); Console.WriteLine( "this task id {0}", Task.CurrentId); Console.WriteLine( "do some cleanup"); }# endregion
下面是超链接,点击就可以过去)
C# 看懂这100+行代码,你就真正入门了(经典)
C# WPF项目实战(经典)
C# NOPI 项目实战(经典)(可下载项目源码) WPF【框架学习】MVVM初探(经典)
C# action,delegate,func的用法和区别
C#接口的作用(经典)
C# 三种方式实现Socket数据接收(经典)
C#实例(经典):四路光电开关&激光雷达数据采集和波形图绘制
技术群:
小编微信:mm1552923
公众号:dotNet编程大全