X
usingSystem;usingSystem.Collections.Generic;namespaceparallel.foreach{classProgram {//The code structure should be like this ... But the logic in the method test in the real world is much more complex ... Static voidMain (string[] args) { //test Data ...list<int> intlist =Newlist<int>(); for(inti =0; I < -; i++) {Intlist.add (i); }
The problem is that when you execute this method, you get an error ... System.Threading.Tasks.Parallel.ForEach (Intlist, (IModel)={Test (IModel);}); } /// <summary> ///here is just a test method, the actual method of the logic is more complex .../// </summary> /// <param name= "i" ></param> Public Static voidTest (inti) {int tempi = 0;//when Maxdegreeofparallelism is set to 3 or above, an error is made, debugging-adding parallel monitoring-you will see "tempi" several times without a declaration. .. {The name ' tempi ' does not exist in the current context}
Tempi = i + 1;
Console.WriteLine (tempi); } }}
The first search has not been searched ... Multithreading is really a little bit less ... Ha ha...
Finally in the CSDN saw the results of the program, a perennial active in the CSDN forum, the old-timers gave the correct answer ... Transmission Door
Private Static Object New Object (), and then read and write the variables with mutual exclusion, such as Lock (lockflag) { var x = Listinfo[i]; Listinfo.remove (x);}
Remember later, multi-threading, remember lock ... Lock ...
X
Parallel.ForEach multithreaded declaration failed "object reference not set to an instance of an object"