ThunD3eR
ThunD3eR

Reputation: 3436

How can I know if there are any active threads?

I have a console application that when it is running sends emails through googles smtp client.

Code for this:

private void SendEmailThread(MailMessage message)
{
    Thread thread = new Thread(() => _mailService.SendEmail(message));
    thread.Start();
    thread.Join();
}

How do I know when all threads are completed?

Is there a global property that is set to ThreadsRunning = 0 when all are done?

I would like to send a message to the console when all emails have been sent and that is done when I have no more threads.

Something like:

if(allThreadsDone){
    Console.WriteLine("All mails are sent");
}

Upvotes: 0

Views: 78

Answers (1)

TheLethalCoder
TheLethalCoder

Reputation: 6746

Your code is actually (more or less) running synchronously. This is because Thread.Join blocks the calling thread until the other thread ends. Or as MSDN puts it:

Blocks the calling thread until the thread represented by this instance terminates, while continuing to perform standard COM and SendMessage pumping.

So essentially all you need to do is after the last call to SendEmailThread just print your message:

Console.WriteLine("All mails are sent");

For what you are trying to achieve I suggest you look into Task.WhenAll. In your case something like:

var tasks = new List<Task>();
foreach (var message in messages)
{
    tasks.Add(Task.Run(() => _mailService.SendEmail(message)));
}

Task waiter = Task.WhenAll(tasks);
try
{
   waiter.Wait();
}
catch {}   

if (waiter.Status == TaskStatus.RanToCompletion)
{
    Console.WriteLine("All messages sent.");
}
else
{
    Console.WriteLine("Some messages failed to send.");  
}

Upvotes: 3

Related Questions