我正在運行正在發送郵件的線程。我怎麼知道線程已經完成執行?獲取線程狀態
new Thread(x => SendMail(node.Attributes["id"].Value.ToString(), node["fname"].InnerText + " " + node["lname"].InnerText, 500, node["email"].InnerText)).Start();
我正在運行正在發送郵件的線程。我怎麼知道線程已經完成執行?獲取線程狀態
new Thread(x => SendMail(node.Attributes["id"].Value.ToString(), node["fname"].InnerText + " " + node["lname"].InnerText, 500, node["email"].InnerText)).Start();
除了安德魯的回答,您可以使用的BackgroundWorker它已經有您正在使用.NET 4 RunWorkerCompleted事件 BackgroundWorker
您應該保留對您創建的線程實例的引用,然後檢查ThreadState
。您還可以檢查IsAlive
屬性以查看線程當前是否正在執行。
var thr = new Thread(x => SendMail(node.Attributes["id"].Value.ToString(), node["fname"].InnerText + " " + node["lname"].InnerText, 500, node["email"].InnerText));
thr.Start();
thr.Join();//In this place main thread will wait
這取決於你的環境是什麼。例如,您可以通過使用任務並訂閱延續來避免所有線程。
例如
var task = Task.Run(DoSomething)
.ContinueWith(a => Whatever())
或者通過使用C#5中給出的方便關鍵字:
var task = await Task.Run(DoSomething);
Whatever();
如果必須使用線程,我建議通過一個委託,當電子郵件完成你剛纔叫它:
// Outside the thread
private Action callback;
// Before starting the thread
callback = MyMethod/*Or a lambda if you want*/;
// In the thread action
Action<object> threadBody = x =>
{
SendMail(node.Attributes["id"].Value.ToString(), node["fname"].InnerText + " " + node["lname"].InnerText, 500, node["email"].InnerText);
callback();
};
另一種變化是結合ManualResetEvent
使用ThreadPool.QueueUserWorkItem
:
如:
private void DoWork()
{
List<ManualResetEvent> events = new List<ManualResetEvent>();
//in case you need to loop through multiple email addresses
//use the foreach here, assuming that the items is a list.
//foreach(var item in items)
//{
var resetEvent = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(arg =>
{
SendMail(node.Attributes["id"].Value.ToString(),
node["fname"].InnerText + " " + node["lname"].InnerText,
500, node["email"].InnerText);
resetEvent.Set();
});
events.Add(resetEvent);
//} <- closes the foreach loop
//WaitHandle.WaitAll waits for all the threads to finish.
WaitHandle.WaitAll(events.ToArray());
MessageBox.Show("Mails are sent", "Notification");
}
這將是在特別的情況下有用,你通過電子郵件地址列表或數組要循環和單獨啓動每個郵件線程。
在你的情況下,如果你想等待郵件發送時做其他事情。您可以簡單地在後臺線程中運行上面的代碼,並在消息顯示您知道工作已完成時。
public void StartMailThread()
{
Thread myThread = new Thread(DoWork)
{
IsBackground = true,
Name = "MailThread"
};
myThread.Start();
}
儘管使用線程啓動線程池似乎對我來說有點奇怪。
?如果是這樣,使用'任務'將是一個更好的主意IMO。 –
您需要知道線程的狀態或是否調用並退出'SendMail'方法? – sll
在做其他工作時,我需要得到通知,說明該線程是否已完成執行,並向用戶發出完成任務已完成的消息 – user1844205