如何从BeginInvoke返回T值?

Cha*_*Shi 1 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);
    }
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ell 6

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

return actionFunction();
Run Code Online (Sandbox Code Playgroud)

这将减少开销.

如果你想要异步,而你是4.0,那么TPL可能是一个不错的选择:

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

现在调用者可以使用:

var task = BeginInvokeExWithReturnValue(() => Whatever());
Run Code Online (Sandbox Code Playgroud)

然后在需要时,检查完成,阻止(Wait)完成,注册继续等.或者只是:

var result = task.Result; // implicit wait
Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)

这允许您无缝地编写异步代码.或者在C#5.0中,无缝地编写延续:

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