1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Task/Parallel实现异步多线程

Task/Parallel实现异步多线程

时间:2019-02-04 01:33:05

相关推荐

Task/Parallel实现异步多线程

代码:

#region Task 异步多线程,Task是基于ThreadPool实现的{//TestClass testClass = new TestClass();//Action<object> action = new Action<object>(t => testClass.TestThread(t.ToString()));//TaskFactory taskFactory = new TaskFactory();//List<Task> taskList = new List<Task>();//for (int i = 0; i < 5; i++)//{// Task task = taskFactory.StartNew(action, "task" + i);// taskList.Add(task);//}//同步等待////1.1所在线程等待,目前在主线程,等待某一个Task执行完毕,只要有一个完成,就继续往下执行。会卡住主线程。//Task.WaitAny(taskList.ToArray());//Console.WriteLine("某一个Task执行完毕");////1.2所在线程等待,目前在主线程,直到所有Task执行完毕;会卡住主线程。//Task.WaitAll(taskList.ToArray());//Console.WriteLine("所有Task执行完毕");////2.1回调等待////不卡主线程,所有Task完成,才执行下面的操作//taskFactory.ContinueWhenAll(taskList.ToArray(), taskArray =>//{// Console.WriteLine("taskFactory.ContinueWhenAll {0}", Thread.CurrentThread.ManagedThreadId);// foreach (var item in taskArray)// {// Console.WriteLine(item.AsyncState);// Console.WriteLine(item.IsCompleted);// }//});////2.2回调等待////不卡主线程,有一个Task完成,就执行下面的操作//taskFactory.ContinueWhenAny(taskList.ToArray(), taskAction =>//{// Console.WriteLine("taskFactory.ContinueWhenAny {0}", Thread.CurrentThread.ManagedThreadId);// Console.WriteLine(taskAction.AsyncState);// Console.WriteLine(taskAction.IsCompleted);//}); }#endregion#region Parallel 基于Task实现,多个任务并行计算,主线程也会计算,其实就是Task+WaitAll,一定会卡住主线程{//Console.WriteLine("主线程的ID:{0}", Thread.CurrentThread.ManagedThreadId);//Parallel.Invoke(() => { Console.WriteLine("当前线程的ID:{0}", Thread.CurrentThread.ManagedThreadId); },// () => { Console.WriteLine("当前线程的ID:{0}", Thread.CurrentThread.ManagedThreadId); },// () => { Console.WriteLine("当前线程的ID:{0}", Thread.CurrentThread.ManagedThreadId); },// () => { Console.WriteLine("当前线程的ID:{0}", Thread.CurrentThread.ManagedThreadId); },// () => { Console.WriteLine("当前线程的ID:{0}", Thread.CurrentThread.ManagedThreadId); });////全部完成后,进入下一步,看上去就像同步编程//Parallel.ForEach<int>(new int[] { 1, 2, 3, 4, 5 }, t =>//{// Console.WriteLine("当前线程ID:{0},结果:{1}", Thread.CurrentThread.ManagedThreadId, t * t);// Thread.Sleep(100);//});//ParallelOptions options = new ParallelOptions(){MaxDegreeOfParallelism = 5};Parallel.For(0, 1000, options, t => { Console.WriteLine("结果:" + t.ToString()); });Parallel.For(0, 1000, options, (t, state) => {Console.WriteLine("结果:" + t.ToString());//state.Break();////state.Stop();////return;});}#endregion

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。