class Program { static void Main(string[] args) { Task t = new Task(DoA); t.Start(); Console.ReadKey(); } static void DoA() { for (int i = 0; i < 100; i++) { Console.WriteLine("i={0}\n", i); } } }
2)通过Run,直接运行,接受参数一个Action,返回对象是一个Task
static void Main(string[] args) { Task.Run(() => { for (int i = 0; i < 50; i++) { Console.WriteLine("i={0}",i); } }); Console.ReadKey(); }
3)带返回参数的线程
Task<int> task = Task.Run<int>(() => { int sum = 0; for (int i = 0; i < 50; i++) { sum += 1; } return sum; }); int result = task.Result; Console.WriteLine("运算结果是:{0}",result);//输出50 Console.ReadKey();
4)通过Task.Factory
Task t = Task.Factory.StartNew(() => { for (int i = 0; i < 10; i++) { Console.WriteLine("i={0}", i); } });
以上是Task用法之启动方法实例的详细内容。更多信息请关注PHP中文网其他相关文章!