C# ThreadPool 等待结果
我想要一个类似的函数:
public static V callAsyncAndWait<V>(Func<V> func)
{
ThreadPool.QueueUserWorkItem(obj =>
{
V v = func.Invoke();
});
return v;
}
显然这段代码无法编译。我想要的是在另一个线程中运行 Func 并返回结果。我怎样才能做到这一点?
I want to have a function to something similar:
public static V callAsyncAndWait<V>(Func<V> func)
{
ThreadPool.QueueUserWorkItem(obj =>
{
V v = func.Invoke();
});
return v;
}
Obviously this code doesn't compile. What I want is to run the Func in another thread and return the result. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您改用新的 .NET 4.0
Task
类。以下是有关如何从执行Task
返回结果的教程:http://msdn.microsoft.com/en-us/library/dd537613.aspx实际上,您有一个非常方便的属性,称为
Result
,在调用getter 将阻塞,直到结果可用。I recommend you to use the new .NET 4.0
Task
class instead. Here is a tutorial on how to return a result from the execution ofTask
: http://msdn.microsoft.com/en-us/library/dd537613.aspxPractically you have a very convenient property called
Result
, which, upon invocation of the getter, will block until the result is available.这没有多大意义。如果该方法应该等待任务完成,那么您根本不需要单独的线程。
像“调用异步并完成后通知”之类的东西更有意义:
That doesn't make too much sense. If the method is supposed to wait for the task to be finished, then you don't need a separate thread at all.
Something like "call async and notify when done" would make more sense:
您可以使用异步模式来做到这一点:
You can use async patternt to do it: