Task是.net 4.0中的一个新特性,提供的功能非常强大,下面是其具体的使用方法演示:
2017-01-22 14:37
791 查看
using System; using System.Threading.Tasks; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { RunnerRaceTest(); Console.WriteLine("into main loop now..."); Console.ReadLine(); } static void RunnerRaceTest() { Task[] tRunners = new Task[10]; for (int i = 0; i < 10; i++) { Console.WriteLine("我是运动员" + i.ToString() + "号,我已经就位"); tRunners[i] = new Task(() => { }); } Console.WriteLine("预备开始,跑..."); Parallel.ForEach(tRunners, i => { i.Start(); Thread.Sleep(2000); Console.WriteLine(i.Id.ToString() + "号运动员已经到达..."); }); Task.WaitAll(tRunners); Console.WriteLine("比赛完毕..."); } //handle ContinueWith method. //TaskContinuationOptions.OnlyOnRanToCompletion means that //only the first task runs successfully, then the continue one will start to run. //ContinueWith的使用方法 /*******运行结果(当第一个TaskContinuationOptions.OnlyOnRanToCompletion时)********* * this is an exception * into main loop now... **********************/ /*******运行结果(当第一个TaskContinuationOptions.OnlyOnFaulted时)********* * exception found in prev task when handling Continuation... * this is continuation... * this is an exception * into main loop now... **********************/ static void TaskContinueWith() { Task t1 = new Task(() => { throw new Exception("this is an exception"); Console.WriteLine("this is task one..."); }); Task t2 = t1.ContinueWith((preTask) => { if (preTask.Exception != null) { Console.WriteLine("exception found in prev task when handling Continuation..."); } Console.WriteLine("this is continuation..."); },TaskContinuationOptions.AttachedToParent|TaskContinuationOptions.OnlyOnFaulted); t1.Start(); try { t1.Wait(); t2.Wait(); } catch (AggregateException e) { Console.WriteLine(e.InnerException.Message); } } //handle children tasks //主要是用来测试子任务的运行,利用AttachedToParent来实现子任务功能 /*******运行结果********* * into the first task now... * into the second task now... * into the third task now... * Exception caught :GrandChild exception * into main loop now... **********************/ static void TaskWithChildren() { Task t = new Task(() => //主任务 { Console.WriteLine("into the first task now..."); Task childTask = new Task(() => //第一个子任务 { Console.WriteLine("into the second task now..."); Task grandChildTask = new Task(() => //第二个子任务 { Console.WriteLine("into the third task now..."); throw new Exception("GrandChild exception"); }, TaskCreationOptions.AttachedToParent); grandChildTask.Start(); //开始第二个子任务 }, TaskCreationOptions.AttachedToParent); childTask.Start(); //开始第一个子任务 }); t.Start(); //开启主任务 try { t.Wait(); //同步运行等待 } catch (AggregateException e) { Console.WriteLine("Exception caught : " + e.InnerException.InnerException.InnerException.Message); } } //handle cancellation during task running //主要用来测试任务执行过程中的取消操作 /*******运行结果********* * this is task iteration 1 * the operation has been canceled... * into main loop now... **********************/ static void TaskWithCancellation() { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = cancellationTokenSource.Token; //主要用于任务取消操作的信号量设置 Task t = new Task(() => { int i = 0; while (true) { i++; Thread.Sleep(1000); Console.WriteLine("this is task iteration " + i); cancellationToken.ThrowIfCancellationRequested(); //注册信号量,如果用户取消,那么将会中断在此处 Console.WriteLine("Test to see if below can be excuted..."); Console.WriteLine("I am not excute"); } }, cancellationToken); t.Start(); //开始任务 Thread.Sleep(1000); cancellationTokenSource.Cancel(); //取消任务 try { t.Wait(); } catch (AggregateException e) { if (e.InnerException is OperationCanceledException) Console.WriteLine("the opeartion has been canceled..."); else Console.WriteLine("encounter some unexpected exceptions..."); } } //handle timeout in task running //主要是用来测试任务执行的超时功能 /*******运行结果********* * We are waiting for the task to finish * the task has timed out. * into main loop now... * I started... * *********************/ static void TaskWithTimeout() { Task t = new Task(() => { Thread.Sleep(3000); Console.WriteLine("I started..."); }); t.Start(); //开始任务 Console.WriteLine("We are waiting for the task to finish"); //任务执行的超时时间为2s,程序执行需要3s,所以会出现超时 bool hasNotTimeOut = t.Wait(2000); if (hasNotTimeOut) Console.WriteLine("the task has not timed out."); else Console.WriteLine("the task has timed out."); } //handle exception during task execution. //主要是用来测试任务执行时候的错误捕获功能 /*******运行结果********* * We are waiting for the task to finish * Caught Exception:this is exception in task... * into main loop now... * *********************/ static void TaskWithException() { Task t = new Task(() => { throw new Exception("this is exception in task..."); //当任务执行的时候,出现了Exception Console.WriteLine("I started.."); }); t.Start(); //开始运行任务 Console.WriteLine("We are waiting for the task to finish"); try { t.Wait(); //同步执行 } catch (AggregateException e) //AggregateException可以捕获运行中出现的错误 { Console.WriteLine("Caught Exception:" + e.InnerException.Message); //这里显示 } } //simple use of Task //主要是介绍Task的最简单用法 /*******运行结果********* * started... * into main loop now... * *********************/ static void TaskOfFirst() { Task t = new Task(() => { Console.WriteLine("I started..."); }); //开始运行 t.Start(); //等待任务运行完成,这里将会阻塞主线程,如果去掉,那么主线程和子线程会并行运行 t.Wait(); } } }
相关文章推荐
- 将对setjmp与longjmp的具体使用方法和适用的场合,进行一个非常全面的阐述。
- (五)OpenCV提供一个功能强大的UI接口,可以在MFC、Qt、WinForms、Cocoa等平台下使用
- 将对setjmp与longjmp的具体使用方法和适用的场合,进行一个非常全面的阐述。
- 如何使用 asp.net 4.0 新特性 路由功能 有助于seo优化 给一个 asp.net web项目(网站项目) 增加路由功能 ,继承,给根据路由生成的url的结尾,增加一个有利于seo优化的斜杠 /,跳转到一个路由生成的url页面
- 功能强大易用的Web视频播放器——Flowplayer(使用方法及演示)
- 功能强大的Web视频播放器Flowplayer(使用方法及演示)-转
- 存储过程中使用RETURN语句返回数值,.Net里用ExecuteScalar方法结果将会导致一个未引用到具体对象的异常
- 功能强大易用的Web视频播放器——Flowplayer(使用方法及演示)
- 友盟分享和第三方登录的一个工具类,具体的使用方法直接去友盟官网看,写的非常详细
- 一个perl线程使用方法的简单演示
- 下面的示例演示如何使用传递到事件处理方法的 GridViewCommandEventArgs 对象确定引发事件的按钮的命令名。
- 建立一个使用.Net 2.0 MemberShip功能的标准例程(二)——配置篇
- .net同一个解决方案下面多个web项目的解决方法
- 简单工厂(Factory)-提供一个创建对象实例的功能,而无须关心其具体实现。被创建实例的类型可以是接口、抽象类,也可以是具体的类。
- 安装.net 4.0 后,.net 2.0 程序无法使用解决方法
- 一个功能非常强大的日历控件(可配置)
- 最近在为界面库中增加一个单独的换肤功能,自己记录下GDI渐变色的使用方法
- 大家用了这么久的.net有没有发现C#中可以用中文变量呀!!可用这个特性来彻底改变程序的易读性(搞笑).但其实有一个非常独特的用处的
- 建立一个使用.Net 2.0 MemberShip功能的标准例程(二)——配置篇
- 关于如何删除DataTable中的重复行---使用.Net提供方法