Home > Net >  Parallelism with a shared interlocked variable
Parallelism with a shared interlocked variable

Time:08-19

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?
    
});

CodePudding user response:

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

  •  Tags:  
  • c#
  • Related