U
UL-Tomten
I recently found myself in a situation wanting to
Thread.JoinAll(timeout) (i.e. blocking the calling thread until all a
list of threads have finished or the timeout has expired). I wanted to
do this using only managed threading[1], which means Monitors instead
of WaitHandles. I also didn't want to assume the threads were worker
threads in the thread pool. The solution I came up with resembles the
one described in Joseph Albahari's "Threading in C#" E-book[2]. The
problem is, I (and it) relied on
a. locking, Wait()ing and Pulse()ing to control flow
b. decreasing an "number of active threads" counter
c. keeping track of how much of the desired timeout has passed
d. assuming everything is done when the counter reaches 0
Even though it seems to work, it seems rather kludgy for something
that is more or less 1 line of code if you use the thread pool and
WaitAll(). Can any of you think of a neater solution?
1: From the .NET Framework developer's guide: "Monitor objects are
purely managed, fully portable, and might be more efficient in terms
of operating-system resource requirements. WaitHandle objects
represent operating-system waitable objects, are useful for
synchronizing between managed and unmanaged code, and expose some
advanced operating-system features like the ability to wait on many
objects at once."
2: http://www.albahari.com/threading/part3.html (with working example
implementation)
Thread.JoinAll(timeout) (i.e. blocking the calling thread until all a
list of threads have finished or the timeout has expired). I wanted to
do this using only managed threading[1], which means Monitors instead
of WaitHandles. I also didn't want to assume the threads were worker
threads in the thread pool. The solution I came up with resembles the
one described in Joseph Albahari's "Threading in C#" E-book[2]. The
problem is, I (and it) relied on
a. locking, Wait()ing and Pulse()ing to control flow
b. decreasing an "number of active threads" counter
c. keeping track of how much of the desired timeout has passed
d. assuming everything is done when the counter reaches 0
Even though it seems to work, it seems rather kludgy for something
that is more or less 1 line of code if you use the thread pool and
WaitAll(). Can any of you think of a neater solution?
1: From the .NET Framework developer's guide: "Monitor objects are
purely managed, fully portable, and might be more efficient in terms
of operating-system resource requirements. WaitHandle objects
represent operating-system waitable objects, are useful for
synchronizing between managed and unmanaged code, and expose some
advanced operating-system features like the ability to wait on many
objects at once."
2: http://www.albahari.com/threading/part3.html (with working example
implementation)