我需要使用异步委托调用一个函数,当我浏览AsyncCallback的教程时,我看到异步调用的定义如下:
static void CallbackMethod(IAsyncResult result)
{
// get the delegate that was used to call that
// method
CacheFlusher flusher = (CacheFlusher) result.AsyncState;
// get the return value from that method call
int returnValue = flusher.EndInvoke(result);
Console.WriteLine("The result was " + returnValue);
}
如果我可以从函数中获取返回值,请告诉我。例如:=我的函数格式为
void GetName(int id,ref string Name);
这里我通过引用变量获取函数的输出。如果我使用异步委托调用此函数,我如何读取回调函数的输出?
答案 0 :(得分:1)
您需要将参数包装到对象中:
class User
{
public int Id { get; set; }
public string Name { get; set; }
}
void GetName(IAsyncResult result)
{
var user = (User)result.AsyncState
// ...
}
AsyncCallback callBack = new AsyncCallback(GetName);
答案 1 :(得分:0)
不要通过ref
参数传回返回值。而是将签名更改为:
string GetName(int id)
或可能:
string GetName(int id, string defaultName) // Or whatever
请注意,“引用”和“引用传递”之间存在很大差异。理解这种区别非常重要。