Parallel.For(0, 20, () => { // invoked once for each thread // 对每个线程只初化一次 Console.WriteLine("init thread {0}, task {1}", Thread.CurrentThread.ManagedThreadId, Task.CurrentId); return String.Format("t{0}", Thread.CurrentThread.ManagedThreadId); }, (i, pls, str1) => { // invoked for each member //循环体,str1表示 () =>初始化的值,但只有部分进行了初始化,没有初始化的使用 String.Format("i {0}", i);上一次赋值结果 Console.WriteLine("body i {0} str1 {1} thread {2} task {3}", i, str1, Thread.CurrentThread.ManagedThreadId, Task.CurrentId); Thread.Sleep(10); return String.Format("i {0}", i); }, (str2) => { // final action on each thread //每个线程的退出方法, str2表示 (i, pls, str1) =>中的返回值 Console.WriteLine("finally {0}", str2); });
转载于:https://blog.51cto.com/kevin130/1130629