异步编程
Posted yeshuimaowei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异步编程相关的知识,希望对你有一定的参考价值。
3.TAP 基于任务的异步编程
1..NET4.0 引入了Task任务,Task的使用
Task task = new Task(()=> { for (int i = 0; i < 1000; i++) { Console.WriteLine("task run"); } }); task.Start();
这是简单的启动任务:下面是task的一些版本
public Task(Action action); public Task(Action action, CancellationToken cancellationToken); public Task(Action action, TaskCreationOptions creationOptions); public Task(Action<object> action, object state); public Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions); public Task(Action<object> action, object state, CancellationToken cancellationToken); public Task(Action<object> action, object state, TaskCreationOptions creationOptions); public Task(Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions);
2.建立一个带取消功能的Task
CancellationTokenSource tokenSource = new CancellationTokenSource(); Task task = new Task(() => { for (int i = 0; i < 1000000; i++) { Console.WriteLine("task run"); } }, tokenSource.Token); task.Start();
这里使用Task的task 将会观察CancellationToken,当调用
tokenSource.Cancel() 即可终止任务
3.使用TaskFactory来创建任务
Task.Factory.StartNew(() => { Console.WriteLine("task is running"); });
4.任务的管理
1.WaitAny
var task1= Task.Factory.StartNew(() => { for (int i = 0; i < 20; i++) { Console.WriteLine("task1 is running"); } }); var task2= Task.Factory.StartNew(() => { Console.WriteLine("task2 is running"); }); var taskid= Task.WaitAny(task1, task2); Console.WriteLine(taskid);
Task.WaitAny(task1, task2) 返回的是完成任务的id,表示只要有一个任务完成就返回完成任务的Id 否则一直阻塞;
2.WaitAll
var task1= Task.Factory.StartNew(() => { for (int i = 0; i < 20; i++) { Console.WriteLine("task1 is running"); } }); var task2= Task.Factory.StartNew(() => { Console.WriteLine("task2 is running"); }); Task.WaitAll(task1, task2); Console.WriteLine("All Task Completed");
WaitAll 将等待所有任务的完成,否则将一直阻塞;
3.ContinueWith
这个最有意思,在传统的同步编程模式下,我们喜欢程序串行执行,然后得到结果,但是在多线程编程中,任务都是并发的,很难再使用同步的方法来编程多线程,但是Task提供了这个ContinueWith,当异步任务完成的时候,接着执行这个ContinueWith,任务执行有返回结果,则使用相应版本的ContinueWith来执行,然后整体的执行就想同步编程那样,很方便;
var task1= Task.Factory.StartNew(() => { for (int i = 0; i < 20; i++) { Console.WriteLine("task1 is running"); } }); task1.ContinueWith((ta)=> { Console.WriteLine("task1 continuewith"); });
带返回值版本:
var task1= Task.Factory.StartNew(() => { for (int i = 0; i < 20; i++) { Console.WriteLine("task1 is running"); } return "Hello,world"; }); task1.ContinueWith((ta)=> { Console.WriteLine("task1 continuewith reulst"+ta.Result); });
4.任务的阻塞
var task1= Task.Factory.StartNew(() => { for (int i = 0; i < 20; i++) { Console.WriteLine("task1 is running"); } return "Hello,world"; }); task1.Wait(); Console.WriteLine("task1 completed");
waite 将阻塞线程,知道task的完成
以上是关于异步编程的主要内容,如果未能解决你的问题,请参考以下文章