Parallel.ForEach multithreaded declaration failed "object reference not set to an instance of an object"

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.