user609926
user609926

Reputation: 831

Periodically check to see if all threads have completed

I have an multithreaded application and I want to be able to use a timer to periodically check to see if all threads have finished before starting a new one, ie:

var checkStatusTimer = new System.Threading.Timer(new TimerCallback(CheckThreads), null, 10000, 10000);

This is as far as I've come. What would need to go in the CheckThreads Method to check to see if they're done? I was thinking of something along the lines of a function that checks them like:

                foreach (Thread thread in Threads)
            {
                Thread t = thread;
                if (t.ThreadState != ThreadState.Stopped)
                    return false;
            }

Am I on the right track? is this the correct way to go about this? Or should I use a System.Timers.Timer instead? Also, the function form within I want to do this periodic check is static. Any help would be appreciated.

Upvotes: 0

Views: 280

Answers (2)

Ed Power
Ed Power

Reputation: 8531

@usr's task-based approach is best, but if you must rely on threads, then I suggest that as each thread is completes it invokes a method that removes the thread from your Threads collection. Then all you have to do in your timer callback is to check the count of the collection. Relying on ThreadState is not advisable.

Upvotes: 0

usr
usr

Reputation: 171236

Use Task instead of Thread. Then, you can create a combined task:

Task[] tasks = ...; //You provide this
Task combined = Task.WhenAll(tasks);

Now you can check for completion: combined.IsCompleted. You can also Wait and await that task.

Thread is a legacy API that is rarely a good idea to use.

Upvotes: 1

Related Questions