C# 异步回调通过引用变量获取值
我需要使用异步委托调用函数,当我阅读异步回调教程时,我看到异步回调定义如下:C# 异步回调通过引用变量获取值,c#,.net,asynchronous,asynccallback,C#,.net,Asynchronous,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
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);
在这里,我通过一个引用变量获得函数的输出。如果使用异步委托调用此函数,如何读取回调函数的输出?不要通过
ref
参数传回返回值。相反,将签名更改为:
string GetName(int id)
或者可能:
string GetName(int id, string defaultName) // Or whatever
请注意,“引用”和“通过引用传递”之间有很大的区别。理解区别很重要。您需要将参数包装到对象中:
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);