简体   繁体   中英

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. How can I do that?

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 of Task : http://msdn.microsoft.com/en-us/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.

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:

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

  asyncresult.AsyncWaitHandle.WaitOne();

  return func.EndInvoke(asyncResult);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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