如何获取在回调中传递给异步方法的参数(而不是lambda)

时间:2011-07-02 11:14:54

标签: c# asynchronous lambda callback

  

可能重复:
  How to get the parameters passed to the asynchronous method in the callback

我需要将此lambda转换为方法回调

var sendRegistrationDelegate =
    new AsyncSendRegistrationDelegate(AsyncSendRegistrationMethod);

sendRegistrationDelegate.BeginInvoke(registrationToUser, label, ar =>
{
    var responceFromServer = sendRegistrationDelegate.EndInvoke(ar);

    if (responceFromServer.IsError)
    {
        SetText(label, registrationToUser.Name + @" " +
            responceFromServer.ErrorMessage);
    }
    else
    {
        SetText(label, registrationToUser.Name + @" " +
            responceFromServer.Data);
    }
}, null);

1 个答案:

答案 0 :(得分:0)

首先,您是否掌握了lambdas和匿名代表?

在此片段中:

    sendRegistrationDelegate.BeginInvoke(registrationToUser, label, ar =>
    // start of method
    {
        var responceFromServer = sendRegistrationDelegate.EndInvoke(ar);

        if (responceFromServer.IsError)
        {
            SetText(label, registrationToUser.Name + @" " +
                responceFromServer.ErrorMessage);
        }
        else
        {
            SetText(label, registrationToUser.Name + @" " +
                responceFromServer.Data);
        }
    }
   // end of method
     , null);

...开始和结束{ }标记方法的开头和结尾,如下所示:

void AsyncCallbackMethod(IAsyncResult ar)
{
    // method body
}

您的BeginInvoke方法如下所示:

sendRegistrationDelegate.BeginInvoke(registrationToUser, label, new AsyncCallback(AsyncCallbackMethod), null);