我想写一个类来简化异步编程,比如 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/