Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parallelism with a shared interlocked variable

Is there a way to share a variable amongst a parallel method? I have this current.
I know there is a way to do this but I can’t seem to find the code amongst the microsoft documents on how to do it. I think its some type of lock or interlock, but can’t seem to find it.

List<string> bob = new List<string>();

bob.Add("hey");
bob.Add("asdasf");
bob.Add("dfghfghd");
bob.Add("rtertdf");
bob.Add("2535dfgd");
bob.Add("sdfsdfzcxv");
bob.Add("sfgsdgsdfh");
bob.Add("23454567");
bob.Add("fgjuoiyhji");
bob.Add("ghjnbvdfg");
bob.Add("fghdtu5645");
bob.Add("565yhfhgh");
bob.Add("ewqrwy77684");
bob.Add("nbndrthw2");
Parallel.ForEach(bob, peer =>
{
    Console.WriteLine(peer + " : " + currentCount); // how can I make currentCount shared?
    
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can just do this. You were almost there. Just need to use an Interlocked.Increment on counter.

int count = 0;
List<string> bob = new List<string>();

bob.Add("hey");
bob.Add("asdasf");
bob.Add("dfghfghd");
bob.Add("rtertdf");
bob.Add("2535dfgd");
bob.Add("sdfsdfzcxv");
bob.Add("sfgsdgsdfh");
bob.Add("23454567");
bob.Add("fgjuoiyhji");
bob.Add("ghjnbvdfg");
bob.Add("fghdtu5645");
bob.Add("565yhfhgh");
bob.Add("ewqrwy77684");
bob.Add("nbndrthw2");
Parallel.ForEach(bob, peer =>
{
    var currentCount = Interlocked.Increment(ref count);
    Console.WriteLine(peer + " : " + currentCount);
    
});

this produces

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading