如何获取在回调中传递给异步方法的参数

时间:2011-07-02 00:34:38

标签: c# callback c#-2.0 asynccallback

我需要一个传输到CallbackMethodSendRegistration中的AsyncSendRegistrationMethod的Label。

private delegate ResponceFromServer AsyncSendRegistrationDelegate(RegistrationToUser registrationToUser, Label label);
private ResponceFromServer AsyncSendRegistrationMethod(RegistrationToUser registrationToUser, Label label)
{
    SetText(label,  registrationToUser.Name + " registration...");


    return Requests.DataBase.Authorization.Registration(
        registrationToUser.Name, 
        registrationToUser.IdRoleUser, 
        registrationToUser.IdGroup);
}
private void CallbackMethodSendRegistration(IAsyncResult ar)
{
    var sendRegistrationDelegate = (AsyncSendRegistrationDelegate)ar.AsyncState;

    var responceFromServer = (ResponceFromServer)sendRegistrationDelegate.EndInvoke(ar);
    if(responceFromServer.IsError)
    {
       //here need label.Text
    }
    else
    {

    }
}

1 个答案:

答案 0 :(得分:3)

获取对传递给sendRegistrationDelegate的标签的引用的一种方法是使回调为lambda。在呼叫站点,这将是这样的:

    var registrationToUser = ...;
    var label = ...;

    sendRegistrationDelegate.BeginInvoke(registrationToUser, label, ar =>
    {
        var responceFromServer  = sendRegistrationDelegate.EndInvoke(ar);
        if (responceFromServer.IsError)
        {
            label.Text = "";
        }
        else
        {

        }
    }, null);