2

我需要使用异步委托调用函数,当我浏览 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);

在这里,我通过引用变量获取函数的输出。如果我使用异步委托调用此函数,我如何读取回调函数的输出?

4

2 回答 2

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);
于 2011-07-05T12:30:55.467 回答
0

不要通过ref参数传回返回值。相反,将签名更改为:

string GetName(int id)

或者可能:

string GetName(int id, string defaultName) // Or whatever

请注意,“引用”和“通过引用”之间存在很大差异。了解区别很重要。

于 2011-07-05T12:29:00.117 回答