连续任务
using System; using System.Text; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Test { class Program { public static string DateTime_Now_ToString() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } /// <summary> /// 连续任务(对任务进行排序) /// </summary> static void Main() { Console.WriteLine("当前时间:{0}\n", DateTime_Now_ToString()); //前置任务 Task<int> task1 = new Task<int>(() => { Console.WriteLine("task1任务开始," + DateTime.Now.ToString()); Thread.Sleep(TimeSpan.FromMilliseconds(5000)); int threadId = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("task11内的线程Id:{0},{1}", threadId.ToString(), DateTime.Now.ToString()); CurrentThreadInfo("task11"); return threadId; });
//后置任务(task1的后置任务) Task task1Continue = task1.ContinueWith(t1 => { //Task.ContinueWith()方法新建一个连续任务,t1作为参数传递一个对前置任务(task1)的引用。 Console.WriteLine("\ntask1Continue任务开始," + DateTime.Now.ToString()); int threadId = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("task1Continue内的线程Id:{0},{1}", threadId.ToString(), DateTime.Now.ToString()); CurrentThreadInfo("task1Continue"); Thread.Sleep(TimeSpan.FromMilliseconds(2000)); Console.WriteLine("\n前置任务的结果:【{0}】,{1}", t1.Result.ToString(), DateTime.Now.ToString()); }); task1.Start(); Task.WaitAll(task1, task1Continue);//等待两个任务完成 Console.WriteLine("\n执行完成" + DateTime_Now_ToString()); Console.ReadLine(); } /// <summary> /// 当前线程信息 /// </summary> private static void CurrentThreadInfo(string name) { StringBuilder builder = new StringBuilder(); builder.AppendLine(""); builder.AppendLine(String.Format("{0}线程Id:\t\t{1}", name, Thread.CurrentThread.ManagedThreadId)); builder.AppendLine(String.Format("{0}是否使用线程池:\t{1}", name, Thread.CurrentThread.IsThreadPoolThread)); builder.AppendLine(String.Format("{0}是否后台线程:\t{1}", name, Thread.CurrentThread.IsBackground)); builder.AppendLine(String.Format("{0}线程状态:\t\t{1}", name, Thread.CurrentThread.ThreadState.ToString())); builder.AppendLine(String.Format("{0}当前时间:\t\t{1}", name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); builder.AppendLine(""); Console.WriteLine(builder.ToString()); } } }
打印运行结果:
/* 当前时间:2016-09-01 10:32:10 task1任务开始,2016/9/1 10:32:10 task11内的线程Id:6,2016/9/1 10:32:15 task11线程Id: 6 task11是否使用线程池: True task11是否后台线程: True task11线程状态: Background task11当前时间: 2016-09-01 10:32:15 task1Continue任务开始,2016/9/1 10:32:15 task1Continue内的线程Id:11,2016/9/1 10:32:15 task1Continue线程Id: 11 task1Continue是否使用线程池: True task1Continue是否后台线程: True task1Continue线程状态: Background task1Continue当前时间: 2016-09-01 10:32:15 前置任务的结果:【6】,2016/9/1 10:32:17 执行完成2016-09-01 10:32:17 */

浙公网安备 33010602011771号