Worker threads and Waitall, Waitany waitone

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello

I'm trying to avoid using the win32 api just to utilize the WaitForMultipleObjects call. Is there an eqivalent in c#
The reason is, I'm trying to kickoff multiple threads, then block until one, any or all of the threads has returned then continue some other task.

Psuedo Code
MAX = 1
count =
start main loop to kick off 100 thread
Increment coun
If count gte MAX thread
.....DO SOME(alot of) WAITING....
decrement coun
els
start new threa
end loo

.....DO SOME WAITING FOR REMAINIG THREADS TO COMPLETE....

cleanup and exi
 
Shaun Miller said:
I'm trying to avoid using the win32 api just to utilize the
WaitForMultipleObjects call. Is there an eqivalent in c#?

There's ManualResetEvent, AutoResetEvent and Mutex, all of which derive
from WaitHandle, which has various Wait* methods.

Alternatively, you could build a semaphore out of monitors, and get
each of the threads to "produce" in the semaphore, calling "aquire"
(whatever you want to call those methods) from the main thread once.
Whichever thread finishes first will unblock the main thread.
 
Shaun Miller said:
Hello,

I'm trying to avoid using the win32 api just to utilize the
WaitForMultipleObjects call. Is there an eqivalent in c#?
The reason is, I'm trying to kickoff multiple threads, then block until
one, any or all of the threads has returned then continue some other task.
Psuedo Code:
MAX = 10
count = 0
start main loop to kick off 100 threads
Increment count
If count gte MAX threads
.....DO SOME(alot of) WAITING.....
decrement count
else
start new thread
end loop

.....DO SOME WAITING FOR REMAINIG THREADS TO COMPLETE.....

cleanup and exit

Shaun,

The .net framework has a WaitHandle class, with functions like WaitOne,
WaitAny and WaitAll. You seem to know that already. Use the event classes in
the .net framework, they derive from WaitHandle (like John mentioned:
ManualResetEvent, AutoResetEvent, Mutex).

Your worker threads could expose an event (Manual or Auto) that signals
completion of the worker thread. To wait until any (or all) have finished,
use WaitHandle.WaitAny.

WaitHandle[] handles = new WaitHandle[numberOfWorkerThreads];
// initialize handles with the completion events of worker threads
int firstIndex = WaitHandle.WaitAny( handles );

http://msdn.microsoft.com/library/d.../frlrfsystemthreadingwaithandleclasstopic.asp
http://msdn.microsoft.com/library/d...stemthreadingwaithandleclasswaitanytopic1.asp

HTH,
 
Back
Top