我有一个控制台应用程序,它运行时通过谷歌smtp客户端发送电子邮件。如何知道是否有活动的线程?
代码如下:
private void SendEmailThread(MailMessage message)
{
Thread thread = new Thread(() => _mailService.SendEmail(message));
thread.Start();
thread.Join();
}
我怎么知道,当所有线程都完成了?
当全部完成后,是否有一个全局属性设置为ThreadsRunning = 0
?
我想在所有电子邮件发送完毕并且没有更多线程时完成消息发送到控制台。
喜欢的东西:
if(allThreadsDone){
Console.WriteLine("All mails are sent");
}
请参阅以下问题:[挂起并通知线程有工作要做时](http://stackoverflow.com/questions/210020/suspending-and-notifying-threads-when-there-is-work-to-做)和[C#相当于Java的等待和通知?](http://stackoverflow.com/questions/209281/c-sharp-equivalent-to-javas-wait-and-notify)。如果您不想要专用的电子邮件发件人线程,请查看['Task.Run'](https://msdn.microsoft.com/zh-cn/library/system.threading.tasks.task.run.aspx) 。 – Romoku
从它的外观来看,你的代码与'_mailService.SendEmail(message);'基本相同,因为你使用'Join'来等待线程完成。 – TheLethalCoder
来自MSDN:阻止调用线程,直到此实例表示的线程终止,同时继续执行标准COM和SendMessage抽取。 – TheLethalCoder