Task
使用的是线程池的线程,全部都是后台线程。不要在Task里面去启动Task。
1.利用Task开启异步多线程:
(1)Task.Run
var task = Task.Run(()=>
this.DoSomethingLong("btnTask_Click")
);
(2)Task.Factory
TaskFactory taskFactory = Task.Factory;// new TaskFactory();
taskFactory.StartNew(() => this.DoSomethingLong("btnTask_Click"));//新开线程 并且启动
2.回调:
(1)当某个线程的任务执行完之后发生回调,但是没有那么精准,不一定是在某个线程完成之后发生。
taskList.Add(taskFactory.StartNew(() => this.DoSomethingLong("btnTask_Click_002")));
taskList.Add(taskFactory.StartNew(() => this.DoSomethingLong("btnTask_Click_001")));
taskList.Add(taskFactory.StartNew(() => this.DoSomethingLong("btnTask_Click_003")));
taskList.Add(taskFactory.StartNew(() => this.DoSomethingLong("btnTask_Click_004")));
taskList.Add(taskFactory.StartNew(() => this.DoSomethingLong("btnTask_Click_005")));
//回调ContinueWhenAny没有那么精准,不一定是在某个线程完成之后发生
taskList.Add(taskFactory.ContinueWhenAny(taskList.ToArray(), t => Console.WriteLine($"ContinueWhenAny {Thread.CurrentThread.ManagedThreadId.ToString("00")}")));
(2)当所有线程的任务执行完之后发生回调
taskList.Add(taskFactory.ContinueWhenAll(taskList.ToArray(), tList => Console.WriteLine($"这里是ContinueWhenAll {Thread.CurrentThread.ManagedThreadId.ToString("00")}")));
(3)单个线程回调
Task task2 = taskFactory.StartNew(t => this.DoSomethingLong("btnTask_Click_005"), "煎饼果子")
.ContinueWith(t => Console.WriteLine($"这里是{t.AsyncState}的回调"));
3.等待:
(1)等待某个任务完成
Task.WaitAny(taskList.ToArray());//卡界面
(2)等待所有任务完成
Task.WaitAll(taskList.ToArray());//卡界面
4.获取返回结果:
Task<int> intTask = taskFactory.StartNew(() => 123);
int iResult = intTask.Result;