简体   繁体   English

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

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

I have a web page that has a form to add devices. 我有一个网页,其中有一个添加设备的表单。

When a user adds a device, the device is registered in 4 different places. 用户添加设备时,该设备会在4个不同的位置注册。 Since each of these 4 registrations takes time I decided to use asynchronous calls. 由于这4个注册中的每一个都需要时间,因此我决定使用异步调用。

So, when the user clicks the save button an AJAx request is fired to the server and invokes the "Save" method. 因此,当用户单击“保存”按钮时,将向服务器触发AJAx请求并调用“保存”方法。 The "Save" method has a loop with an asynchronous call to the "Register" method, like this: “保存”方法具有一个循环,其中包含对“注册”方法的异步调用,如下所示:

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

The problem here is that the "GetRegisteredDevices" call is pointless because the async methods haven't finished yet and there will be no devices to return. 这里的问题是“ GetRegisteredDevices”调用是没有意义的,因为异步方法尚未完成,并且将没有设备可以返回。 Also, I can't update the UI when these actions finish because the main method already returned to the UI. 另外,这些操作完成后,我无法更新UI,因为main方法已经返回到UI。

(I'm ignoring the case here if the user moves the another page right after clicking the "Save" button.) (如果用户在单击“保存”按钮后立即将另一个页面移开,我将忽略这种情况。)

So, is there a way for me to know when all async calls finished and then invoke a method that will update the UI? 那么,有没有办法让我知道所有异步调用何时结束,然后调用将更新UI的方法?

A simplified example of what this might look like using the TPL library and the async/await keywords. 使用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