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

本文关键字:异步方法 参数 获取 回调 | 更新日期: 2023-09-27 18:01:00

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

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
    {
    }
}

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

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

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