问题描述
我想编写一个类来简化异步编程,例如字符串s = mylib.BeginInvoek(test, 1);这是我的代码:
I want to write a class to simplify the asynchronous programing, like string s = mylib.BeginInvoek(test,"1"); here is my code:
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函数返回值。任何人都知道吗,您能帮我吗?
this BeginInvokeExWithReturnValue function has no input parameter, but returns a value,But I don't know how to return a value from BeginInvokeExWithReturnValue function. Anyone who know this, Could you pls help me ? thx very much.
推荐答案
您现在试图做的事情不是异步的。如果您想返回 T
,只需使用:
What you are trying to do right now is not async; if you want to return the T
, just use:
return actionFunction();
这会减少开销。
如果您希望异步,并且您使用的是4.0,那么TPL可能是一个不错的选择:
If you want async, and you are on 4.0, then the TPL may be a good option:
public Task<T> BeginInvokeExWithReturnValue<T>(Func<T> actionFunction)
{
var task = new Task<T>(actionFunction);
task.Start();
return task;
}
现在,呼叫者可以使用:
Now the caller can use:
var task = BeginInvokeExWithReturnValue(() => Whatever());
然后在需要时检查是否完成,阻止(等待$或只是:
and then when desired, check for completion, block (Wait
) for completion, register continuations, etc. Or just:
var result = task.Result; // implicit wait
Console.WriteLine(result);
这可让您无缝编写异步代码。或在C#5.0中,无缝编写延续:
This allows you to seamlessly write async code. Or in C# 5.0, seamlessly write continuations:
var result = await task; // continuation - this is **not** a wait
Console.WriteLine(result);
这篇关于如何从BeginInvoke返回T值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!