AsyncCallback 通过引用变量获取值

发布于 2024-11-19 01:06:32 字数 581 浏览 2 评论 0原文

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

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

I need to call a function using asynchronous delegates, when i go through the tutorial of the AsyncCallback I saw the async call back defined as below:

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);
}       

Please let me know if i can get the return value as reference from the function. eg:= my function is in the format

void GetName(int id,ref string Name);

Here i am getting the output from the function through a reference variable. If i call this function using the async delegates how can i read the output from the callback function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

强辩 2024-11-26 01:06:32

您需要将参数包装到一个对象中:

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);

You need to wrap your arguments into an object:

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);
揽清风入怀 2024-11-26 01:06:32

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

string GetName(int id)

或可能:

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

请注意,“引用”和“按引用传递”之间存在很大差异。理解其中的区别很重要。

Don't pass the return value back via a ref parameter. Instead, change the signature to:

string GetName(int id)

or possibly:

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

Note that there's a big difference between "a reference" and "pass-by-reference". It's important to understand the distinction.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文