Thread Finished Notification?

  • Thread starter Thread starter Will
  • Start date Start date
W

Will

I have a Manager thread that launches a variable number of Worker threads.
When each Worker thread finishes, I want it to notify the Manager thread
that it's done so that the Manager thread can write to a log file or a
database. What's the best way to do this in C#? I'm betting it has a
simple soultion.

I've looked through several examples of multi-threaded programs on the net
and either they don't do what I want or it's just not clicking with me.

Thanks,
Will.
 
Will,

Unfortunately, there is no managed way to do this. In the unmanaged
world, you can just take the thread handle and pass it to
MsgWaitForMultipleObjects, which will let you know when the thread
completes. Unfortunately, there is nothing like that in .NET.

However, you can get around this easily. Give the thread access to a
ManualResetEvent which the thread would call Set on when it is done. Then,
you could pass an array of events to the static WaitAny method on the
WaitHandle class. This will act as a notification for when the thread is
done processing.

Hope this helps.
 
How about just storing a ref to the manager thread class in each worker
class. When the worker is done, it calls a Finished method on the mgr
instance that does the logging.
 
Or you can use standard events to do this - in addition to suggestions of
other posters.
declare event in thread parameters object,
set event handler in main thread before passing object to worker thread
when complete - call event delegate if set.

It's ideal for UI notifications. You have only to remember that delegate
passed will be called on worker thread, so you might need to use
Invoke/BeginInvoke.

And one more - MSMQ. Might be a bit "heavy" apporach, however also useful.

HTH
Alex
 
Back
Top