C # Parallel foreach while loop possible?

I'm not sure how Parallel.foreach's internal thread processing works, and can this guarantee that such a design will work?

Parallel.Foreach(Connections, c => { Input in = c.getInput(); while (in.hasNext()) { object o = in.getNext(); dosomething(o); } } ); 

where in.hasNext () just waits for an object in the input stream and returns true. Basically, I can run a bunch of infinite loops in a parallel foreach structure, ensuring that they all run at the same time.

(For the brave, can I customize this so that I can edit the connection list by adding (and removing, which should be trivial) connections, and it will still read the input of all the connections in the list).

+4
source share
3 answers
  • The number of threads using it is limited, so some elements will be processed one after another.

  • List editing while listing is not good. You will probably get an exception (depending on the list you are using

  • Why not start a new thread for each connection?

Code example:

 public ConnectionOpen(data) { Connection conn=new ... lock(Connections) { Connections.Add(conn); } new Thread(()=> { Receive(conn);//infinite loop goes here }).Start(); } public ConnectionClose(conn) { bool removed=false; lock(Connections) { removed=Connections.Remove(conn); } if(removed) conn.StopReceiving(); } 
0
source

Basically, I can run a bunch of infinite while loops in a parallel foreach structure, ensuring that they all run at the same time

Not. Only a limited number of worker threads will be launched at a time, so if you run more infinite loops than there are threads, the latter will never be executed ...

0
source

Technically, this code will work, but the exact number of threads working โ€œsimultaneouslyโ€ will vary.

In addition to parallel extensions, .NET 4 also added hill elevation and blowing a thread into a thread pool, so basically .NET threadpool will try to add threads to a Parallel.ForEach loop to see if more threads have completed since yours will never complete the number of threads will vary, but I assume it will not be perfect.

Perhaps you will try to use the ParallelWhile construct, the team reported several ways to do this, here is one of them .

0
source

All Articles