码迷,mamicode.com
首页 > 编程语言 > 详细

Task---常用的多线程(基于多线程线程)

时间:2018-04-18 23:31:46      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:start   一个   actor   AC   this   string   eth   任务   splay   

Thread 内容多,不易控制。 Task 好用(必须掌握)。

 

 

技术分享图片
 1 #region Private Method
 2         /// <summary>
 3         /// 一个比较耗时耗资源的私有方法
 4         /// </summary>
 5         /// <param name="name"></param>
 6         private void DoSomethingLong(string name)
 7         {
 8             Console.WriteLine($"****************DoSomethingLong Start {name} {Thread.CurrentThread.ManagedThreadId} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}***************");
 9             long lResult = 0;
10             for (int i = 0; i < 2000000000; i++)
11             {
12                 lResult += i;
13             }
14             //Thread.Sleep(2000);
15 
16             Console.WriteLine($"****************DoSomethingLong   End  {name} {Thread.CurrentThread.ManagedThreadId} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}***************");
17         }
18         #endregion
DoSomethingLong

 

 

声明:

1 Task task = Task.Factory.StartNew(() => this.DoSomethingLong(name));

 

WaitAny() && WaitAll()---卡主线程,卡界面

1             Console.WriteLine("before WaitAny");
2             Task.WaitAny(taskList.ToArray());//当前线程等待某个任务的完成  主线程
3             Console.WriteLine("after WaitAny");
4 
5 
6             Console.WriteLine("before WaitAll");
7             Task.WaitAll(taskList.ToArray());//当前线程等待全部任务的完成  主线程
8             Console.WriteLine("after WaitAll");

 

ContinueWhenAny() && ContinueWhenAll() ---不卡主线程,不卡界面

 1           taskList.Add(Task.Factory.ContinueWhenAny(taskList.ToArray(), t =>
 2                 {
 3                     Console.WriteLine(t.IsCompleted);
 4                     Console.WriteLine($"ContinueWhenAny {Thread.CurrentThread.ManagedThreadId}");
 5                 }));
 6 
 7             taskList.Add(Task.Factory.ContinueWhenAll(taskList.ToArray(), tList =>
 8             {
 9                 Console.WriteLine(tList[0].IsCompleted);
10                 Console.WriteLine($"ContinueWhenAll {Thread.CurrentThread.ManagedThreadId}");
11             }));
12             //回调形式的,全部任务完成后执行的后续动作

 

ContinueWith() 建议少用(嵌套太多,容易晕)

1           //Task taskContinue = task.ContinueWith(t =>
2                 // {
3                 //     Console.WriteLine(t.IsCompleted);
4                 //     Console.WriteLine($"ContinueWhenAny {Thread.CurrentThread.ManagedThreadId}");
5                 // }).ContinueWith(t =>
6                 // {
7                 //     Console.WriteLine(t.IsCompleted);
8                 //     Console.WriteLine($"ContinueWhenAny {Thread.CurrentThread.ManagedThreadId}");
9                 // });

 

Task---常用的多线程(基于多线程线程)

标签:start   一个   actor   AC   this   string   eth   任务   splay   

原文地址:https://www.cnblogs.com/anwser-jungle/p/8878097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!