c# - 如何从 BeginInvoke 返回 T 值?

标签 c# return begininvoke

我想写一个类来简化异步编程,比如 string s = mylib.BeginInvoek(test,"1");这是我的代码:

   public T BeginInvokeExWithReturnValue<T>(Func<T> actionFunction)
    {
        ExecWithReturnType<T> execWtihReturnValue = new ExecWithReturnType<T>(actionFunction);
        IAsyncResult iar = execWtihReturnValue.BeginInvoke(new AsyncCallback(EndInvokeExWithReturnValue<T>), execWtihReturnValue);
        // how to code here to return value
    }

    private void EndInvokeExWithReturnValue<T>(IAsyncResult iar)
    {
        ExecWithReturnType<T> execWtihReturnValue = (ExecWithReturnType<T>)iar.AsyncState;
        execWtihReturnValue.EndInvoke(iar);
    }

这个BeginInvokeExWithReturnValue函数没有输入参数,但是有返回值, 但我不知道如何从 BeginInvokeExWithReturnValue 函数返回一个值。任何知道这个的人,你能帮帮我吗?非常感谢。

最佳答案

您现在尝试做的不是异步的;如果您想返回 T,只需使用:

return actionFunction();

这会减少开销。

如果您想要异步,并且您使用的是 4.0,那么 TPL 可能是一个不错的选择:

public Task<T> BeginInvokeExWithReturnValue<T>(Func<T> actionFunction)
{
    var task = new Task<T>(actionFunction);
    task.Start();
    return task;
}

现在调用者可以使用:

var task = BeginInvokeExWithReturnValue(() => Whatever());

然后在需要时检查是否完成、阻止(等待)完成、注册继续等。或者只是:

var result = task.Result; // implicit wait
Console.WriteLine(result);

这使您可以无缝地编写异步代码。或者在 C# 5.0 中,无缝地编写延续:

var result = await task; // continuation - this is **not** a wait
Console.WriteLine(result);

关于c# - 如何从 BeginInvoke 返回 T 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8789544/

相关文章:

c# - 是否有示例说明为什么应在 NHibernate 中覆盖 Equals/GetHashCode?

android - 如何从 ListView 重新加载 Activity 以更新数据库信息?

c# - GUI何时过载?

c - 如何管理从 C 函数返回的内存

javascript - 函数返回不是我所期望的

c# - 多个 Control.BeginInvoke/Invoke 调用会按顺序执行吗?

c# - 这会导致死锁吗? BeginInvoke()和thread.Join()

c# - Visual Studio 找不到 SingleInstanceFactory

c# - 必须使用关系流畅的 API 或数据注释显式配置此关联的主体端

c# - 密码哈希 - 为什么加盐 60,000 次