Parallel and PLINQ: parallelplinq
Parallel is a simplified Task usage. It contains three static methods: Parallel. For, Parallel. ForEach, and Parallel. Invoke. PLINQ is a parallel version of LINQ. The following are simple examples and precautions for Parallel and PLINQ.
1. Simple Example 1. Parallel.
Int [] nums = new [] {1, 2, 3, 4}; Parallel. for (0, nums. length, I => {Console. writeLine ("subscript: {0}, value: {1}", I, nums [I]);});
2. Parallel. ForEach
Var ltModel = new List <UserInfo> (); for (int I = 1; I <= 5; I ++) {var item = new UserInfo {No = I, name = "Name" + I}; ltModel. add (item);} Parallel. forEach (ltModel, item => {Console. writeLine ("No: {0}, Name: {1}", item. no, item. name );});
3. Parallel. Invoke
Var ltTask = new List <Action> (); for (int I = 1; I <= 5; I ++) {int j = I; ltTask. add () => {Console. writeLine ("START task" + j) ;}) ;} Parallel. invoke (ltTask. toArray ());
4. PLINQ
var ltNum = new List<int>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; var resultNum = (from n in ltNum.AsParallel() where n>=3 orderby n descending select n).ToArray(); foreach (var item in resultNum) { Console.WriteLine("Num: {0}", item); }
Ii. Notes
If you have no requirements on the logical sequence of the set, you can use Parallel and PLINQ. Otherwise, they cannot be used.