Task
.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();
可以有返回值
Thread和ThreadPool都不能有返回值,但Task是可以有返回值的。
1 var result = Task.Factory.StartNew<string>(() =>
2 {
3 return Go1("arg1");
4 });
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
代码执行顺序图解。
运行结果如下图。
漫思



浙公网安备 33010602011771号