samedi 24 octobre 2015

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. Since each of these 4 registrations takes time I decided to use asynchronous calls.

So, when the user clicks the save button an AJAx request is fired to the server and invokes the "Save" method. 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);

        // and to retrieve the results.
        bool returnValue = caller.EndInvoke(result);
    }
    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. Also, I can't update the UI when these actions finish because the main method already returned to the 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?




Aucun commentaire:

Enregistrer un commentaire