繁体   English   中英

C#-如何在异步方法调用后更新网页?

[英]C# - How update a web page after an async method call?

我有一个网页,其中有一个添加设备的表单。

用户添加设备时,该设备会在4个不同的位置注册。 由于这4个注册中的每一个都需要时间,因此我决定使用异步调用。

因此,当用户单击“保存”按钮时,将向服务器触发AJAx请求并调用“保存”方法。 “保存”方法具有一个循环,其中包含对“注册”方法的异步调用,如下所示:

public delegate bool DeviceControllerAsync(...);

public static string Save(...)
{
    //Get all active controllers
    List<Controller> lstControllers = Controller.Get();
    foreach (Controller controller in lstControllers)
    {
        // Invoke asynchronous write method
        DeviceControllerAsync caller = new DeviceControllerAsync(ArubaBL.RegisterDevice);

        // Initiate the asychronous call.
        IAsyncResult result = caller.BeginInvoke(..., null, null);
    }
    return GetRegisteredDevices();
}

这里的问题是“ GetRegisteredDevices”调用是没有意义的,因为异步方法尚未完成,并且将没有设备可以返回。 另外,这些操作完成后,我无法更新UI,因为main方法已经返回到UI。

(如果用户在单击“保存”按钮后立即将另一个页面移开,我将忽略这种情况。)

那么,有没有办法让我知道所有异步调用何时结束,然后调用将更新UI的方法?

使用TPL库和async / await关键字的简化示例。

public static async string Save(...)
{
    //Get all active controllers
    List<Controller> lstControllers = Controller.Get();

    //Create a task object for each async task
    List<Task<returnValueType>> controllerTasks = lstControllers.Select(controller=>{
        DeviceControllerAsync caller = new DeviceControllerAsync(ArubaBL.RegisterDevice);
        return Task.Factory.FromAsync<returnValueType>(caller.BeginInvoke, caller.EndInvoke, null);
    }).ToList();

    // wait for tasks to complete (asynchronously using await)
    await Task.WhenAll(controllerTasks);

    //Do something with the result value from the tasks within controllerTasks
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM