抽象线程之Parallel类
生活随笔
收集整理的這篇文章主要介紹了
抽象线程之Parallel类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
該類定義了并行的For和Foreach方法,Parallel類使用多個任務,因此需要多個線程來完成這個作業
代碼及簡單注釋如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading;namespace ConsoleApplication1 {class Program{//Parallel.For多次調用同一個方法static public void formathod(){//函數原型:Parallel.For<TLocal>(Int32, Int32, Func<TLocal>, Func<Int32, ParallelLoopState, TLocal, TLocal>, Action<TLocal>)//定義一個本地數據為string類型的數據,執行Func<TLocal>委托對本地數據初始化,然后將每個迭代調用一次Func<Int32, ParallelLoopState, TLocal, TLocal>委托,最后執行 Action<TLocal>委托對本地狀態進行最后處理Parallel.For<string>(0, 20, () =>{Console.WriteLine("Task{0} is begin", Task.CurrentId);return string.Format("Task{0}", Thread.CurrentThread.ManagedThreadId);},(i, pls, str) =>{Thread.Sleep(1000);return string.Format("Task{0}", i);},(str) =>{Console.WriteLine("{0} is over", str);});}static public void formathod1(){//函數原型:For(Int32, Int32, Action<Int32>)//以下實例則為從0迭代到10,每一次都調用Action<i>這個委托,返回參數提供了循環是否結束的消息ParallelLoopResult result =Parallel.For(0, 10, i =>{Thread.Sleep(100);Console.WriteLine("Thread{0},Task{1}", Thread.CurrentThread.ManagedThreadId, Task.CurrentId);});Console.WriteLine(result.IsCompleted);}static public void foreachmethod(){//Parallel.ForEach函數原型為:Parallel.ForEach<TSource>(IEnumerable<TSource>, Action<TSource>)//IEnumerable<TSource>為公開枚舉數,該枚舉數支持在指定類型的集合上進行簡單迭代。//以下代碼為迭代集合上的元素,并為他們執行lambda表達式(Action<TSource>委托)string[] data = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };Parallel.ForEach<string>(data, s =>{Thread.Sleep(1000);Console.WriteLine(s);});}static void Main(string[] args){formathod1();formathod();foreachmethod();}} }轉載于:https://www.cnblogs.com/runninglzw/p/3848257.html
總結
以上是生活随笔為你收集整理的抽象线程之Parallel类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言,递归翻转一个单链表,c实现单链表
- 下一篇: 正确的 zip 压缩与解压代码