简体   繁体   English

C#ThreadPool等待结果

[英]C# ThreadPool wait on result

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. 我想要的是在另一个线程中运行Func并返回结果。 How can I do that? 我怎样才能做到这一点?

I recommend you to use the new .NET 4.0 Task class instead. 我建议您改用新的.NET 4.0 Task类。 Here is a tutorial on how to return a result from the execution of Task : http://msdn.microsoft.com/en-us/library/dd537613.aspx 这是有关如何从执行Task返回结果的教程: http : //msdn.microsoft.com/zh-cn/library/dd537613.aspx

Practically you have a very convenient property called Result , which, upon invocation of the getter, will block until the result is available. 实际上,您有一个非常方便的属性称为Result ,在调用getter时,它将阻塞直到结果可用为止。

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: 诸如“调用异步并在完成时通知 ”之类的东西更有意义:

void CallAsyncAndNotifyWhenDone<T>(Func<T> func, Action<T> callback)
{
    ThreadPool.QueueUserWorkItem(obj => 
    {
        T result = func();         
        callback(result);
    });
}

You can use async patternt to do it: 您可以使用异步patternt来做到这一点:

public static V callAsyncAndWait<V>(Func<V> func)
{
  var asyncResult = func.BeginInvoke(null, null);

  asyncresult.AsyncWaitHandle.WaitOne();

  return func.EndInvoke(asyncResult);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM