C#并行和多线程编程
参考:https://www.cnblogs.com/yunfeifei/p/3993401.html 和 https://www.cnblogs.com/rjjs/p/5583722.html 推荐使用TPL
C# TPL(Task Parallel Library)和PLINQ(Parallel LINQ) 并行编程 是.Net4 为多线程编程引入的新的API
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { // create the task Task<int> task1 = new Task<int>(() => { //耗时操作 System.Threading.Thread.Sleep(2000); int sum = 0; for (int i = 0; i < 100; i++) { sum += i; } return sum; }); task1.Start(); Task.Factory.StartNew(() => { //耗时操作 System.Threading.Thread.Sleep(1000); Console.WriteLine("task2在task1之后启动,先完成"); }); // write out the result Console.WriteLine("此处开始于task1.Start和之后task2,却显示在最前面"); Console.WriteLine("Result 1: {0}", task1.Result); Console.ReadLine(); } } }