您可以使用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