您可以使用ManualResetEvent:
public void TaskStartMethod()
{
ManualResetEvent waitHandle = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(o=>
{
// Perform the task here
// Signal when done
waitHandle.Signal();
});
// Wait until the task is complete
waitHandle.WaitOne();
}
從本質上講,傳遞 任務線程池的方法應該是 等待,直到它完成。
上面的代碼是這樣做的,但現在我有一個問題:如果您的方法正在等待任務完成,那麼爲什麼你甚至懶得在單獨的線程上執行任務?換句話說,你所描述的是代碼的順序執行而不是並行執行,所以使用ThradPool
是毫無意義的。
或者,你可能可能需要使用一個單獨的委託作爲回調:
public delegate void OnTaskCompleteDelegate(Result someResult);
public void TaskStartMethod()
{
OnTaskCompleteDelegate callback = new OnTaskCompleteDelegate(OnTaskComplete);
ThradPool.QueueUserWorkItem(o=>
{
// Perform the task
// Use the callback to notify that the
// task is complete. You can send a result
// or whatever you find necessary.
callback(new Result(...));
});
}
public void OnTaskComplete(Result someResult)
{
// Process the result
}
更新(2011/1/24): 你可能甚至不需要回調委託,你可以直接調用OnTaskComplete
和應該做的工作太多:
public void TaskStartMethod()
{
ThradPool.QueueUserWorkItem(o=>
{
// Perform the task
// Call the method when the task is complete
OnTaskComplete(new Result(...));
});
}
是否有任何理由不能使用TPL來做到這一點?如果這對您有用,我可以提出一個好的解決方案。 – 2011-01-21 15:51:32
什麼是TPL? – Fugu 2011-01-21 15:55:11