Chethan
Chethan

Reputation: 300

Check if at least one thread is completed

First of all I am totally new to threading in C#. I have created multiple threads as shown below.

if (flag)
{
    foreach (string empNo in empList)
    {
         Thread thrd = new Thread(()=>ComputeSalary(empNo));
         threadList.Add(thrd);
         thrd.Start();
    }
}

Before proceeding further I need check if at least one thread is completed its execution so that I can perform additional operations.

I also tried creating the list of type thread and by added it to list, so that I can check if at least one thread has completed its execution. I tried with thrd.IsAlive but it always gives me current thread status.

Is there any other way to check if atleast on thread has completed its execution?

Upvotes: 2

Views: 141

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

Here is a solution based on the Task Parallel Library:

// Create a list of tasks for each string in empList
List<Task> empTaskList = empList.Select(emp => Task.Run(() => ComputeSalary(emp)))
                                .ToList();

// Give me the task that finished first.
var firstFinishedTask = await Task.WhenAny(empTaskList); 

A couple of things to note:

  1. In order to use await inside your method, you will have to declare it as async Task or or async Task<T> where T is the desired return type

  2. Task.Run is your equivalent of new Thread().Start(). The difference is Task.Run will use the ThreadPool (unless you explicitly tell it not to), and the Thread class will construct an entirely new thread.

  3. Notice the use of await. This tells the compiler to yield control back to the caller until Task.WhenAny returns the first task that finished.

You should read more about async-await here

Upvotes: 0

Arun Ghosh
Arun Ghosh

Reputation: 7734

You can use AutoResetEvent.

var reset = new AutoResetEvent(false); // ComputeSalary should have access to reset
.....
....

if (flag)
{
    foreach (string empNo in empList)
    {
         Thread thrd = new Thread(()=>ComputeSalary(empNo));
         threadList.Add(thrd);
         thrd.Start();
    }
    reset.WaitOne();
}

.....
.....

void ComputeSalary(int empNo)
{
    .....
    reset.set()
}

Other options are callback function, event or a flag/counter(this is not advised).

Upvotes: 3

Related Questions