码迷,mamicode.com
首页 > 其他好文 > 详细

Task

时间:2016-07-08 19:34:18      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

.net 4.0为我们带来了TPL(Task Parallel Library),其中Task相较ThreadPool线程池使用更简单,而且支持线程的取消,完成和失败通知等交互性操作,而这些是ThreadPool所没有的。并且Task是可以有返回值的。

传参

给异步方法传参,可以使用以下几种方法。

技术分享
  1 new Thread(Go1).Start("arg1");//最原始的传参
  2             new Thread(delegate() //使用匿名委托传参
  3                 {
  4                     Go1("arg1");
  5                 }).Start();
  6             new Thread(() => //使用lambda表达式
  7                 {
  8                     Go1("arg1");
  9                 }).Start();
View Code

可以有返回值

Thread和ThreadPool都不能有返回值,但Task是可以有返回值的。

技术分享
  1 var result = Task.Factory.StartNew<string>(() =>
  2             {
  3                 return Go1("arg1");
  4             });
View Code

Demo

上代码。

技术分享
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading;
  6 using System.Threading.Tasks;
  7 
  8 namespace AsyncCoding
  9 {
 10     class Program
 11     {
 12         static void Main(string[] args)
 13         {
 14             Task.Factory.StartNew(() => //Task默认创建的都是后台线程
 15             {
 16                 Go1("arg1");
 17             });
 18 
 19             Console.WriteLine("我是主线程,Thread Id:{0}", Thread.CurrentThread.ManagedThreadId);
 20             Console.ReadKey();
 21         }
 22 
 23         public static void Go1(string input)
 24         {
 25             Console.WriteLine("我是异步线程,Thread Id:{0},是否为后台线程:{1}, 传入参数为:{2}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsBackground, input);
 26             for (int i = 0; i < 10; i++)
 27             {
 28                 Thread.Sleep(100);//模拟每次执行需要100ms
 29                 Console.WriteLine("异步线程,Thread Id:{0},运行:{1}", Thread.CurrentThread.ManagedThreadId, i);
 30             }
 31         }
 32     }
 33 }
 34 
View Code

代码执行顺序图解。

技术分享

运行结果如下图。

技术分享

Task

标签:

原文地址:http://www.cnblogs.com/mcgrady/p/5654186.html

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