Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for ANY thread to finish, not ALL

I'm starting multiple threads and would like to know when any of then finishes. I know the following code:

foreach (Thread t in threads)
    t.Join();

But it will only wait for all threads together. That's much too late. I need to know when one thread finishes, even when other threads are still running. I'm looking for something equivalent to WaitAny only for threads. But I can't add code to all threads I'm monitoring, so using signals or other synchronisation objects is not an option.

Some clarification: I'm working on a logging/tracing tool that should log the application's activity. I can insert log statements when a thread starts, but I can't insert a log statement on every possible way out of the thread (multiple exit points, exceptions etc.). So I'd like to register the new thread and then be notified when it finishes to write a log entry. I could asynchronously Join on every thread, but that means a second thread for every monitored thread which may seem a bit much overhead. Threads are used by various means, be it a BackgroundWorker, Task or pool thread. In its essence, it's a thread and I'd like to know when it's done. The exact thread mechanism is defined by the application, not the logging solution.

like image 684
ygoe Avatar asked Mar 22 '23 16:03

ygoe


2 Answers

Instead of Threads use Tasks. It has the method WaitAny.

Task.WaitAny

As you can read here,

  • More efficient and more scalable use of system resources.
  • More programmatic control than is possible with a thread or work item.
like image 95
I4V Avatar answered Apr 05 '23 15:04

I4V


In my opinion WaitHandle.WaitAny is the best solution, since you don't like to use it for some xyz reason you can try something like this.

Take the advantage of Thread.Join(int) method which takes millisecond timeout and returns true when thread is terminated or false when timed out.

List<Thread> threads = new List<Thread>();

while (!threads.Any(x=> x.Join(100)))
{

}

You can alter the timeout of Join If you know how long it will take.

like image 23
Sriram Sakthivel Avatar answered Apr 05 '23 17:04

Sriram Sakthivel