【问题标题】:AsyncCallback getting values through reference variableAsyncCallback 通过引用变量获取值
【发布时间】:2011-09-28 18:48:03
【问题描述】:

我需要使用异步委托调用一个函数,当我阅读 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);
}       

如果我可以从函数中获取返回值作为参考,请告诉我。 eg:= 我的函数格式为

void GetName(int id,ref string Name);

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

【问题讨论】:

    标签: c# .net asynchronous asynccallback


    【解决方案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);
    

    【讨论】:

      【解决方案2】:

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

      string GetName(int id)
      

      或者可能:

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

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

      【讨论】:

        猜你喜欢
        • 2022-07-16
        • 1970-01-01
        • 1970-01-01
        • 2017-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-19
        相关资源
        最近更新 更多