C# ThreadPool 等待结果

发布于 2024-12-29 02:23:28 字数 286 浏览 1 评论 0原文

我想要一个类似的函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

海之角 2025-01-05 02:23:28

我建议您改用新的 .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 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.

凉城凉梦凉人心 2025-01-05 02:23:28

这没有多大意义。如果该方法应该等待任务完成,那么您根本不需要单独的线程。

像“调用异步并完成后通知”之类的东西更有意义:

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

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);
    });
}
春风十里 2025-01-05 02:23:28

您可以使用异步模式来做到这一点:

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

  asyncresult.AsyncWaitHandle.WaitOne();

  return func.EndInvoke(asyncResult);
}

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文