C# - 如何在异步方法调用后更新网页?
C# - How update a web page after an async method call?
我有一个网页,其中包含用于添加设备的表单。
当用户添加设备时,该设备会在 4 个不同的地方注册。
由于这 4 个注册中的每一个都需要时间,我决定使用异步调用。
因此,当用户单击保存按钮时,会向服务器发出 AJAx 请求并调用 "Save" 方法。
"Save" 方法有一个异步调用 "Register" 方法的循环,像这样:
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" 调用毫无意义,因为异步方法尚未完成并且没有设备到 return。
此外,当这些操作完成时,我无法更新 UI,因为主要方法已经 returned 到 UI。
(如果用户在单击 "Save" 按钮后立即移动另一页,我将忽略此处的情况。)
那么,有没有办法让我知道所有异步调用何时完成,然后调用一个方法来更新 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
}
我有一个网页,其中包含用于添加设备的表单。
当用户添加设备时,该设备会在 4 个不同的地方注册。 由于这 4 个注册中的每一个都需要时间,我决定使用异步调用。
因此,当用户单击保存按钮时,会向服务器发出 AJAx 请求并调用 "Save" 方法。 "Save" 方法有一个异步调用 "Register" 方法的循环,像这样:
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" 调用毫无意义,因为异步方法尚未完成并且没有设备到 return。 此外,当这些操作完成时,我无法更新 UI,因为主要方法已经 returned 到 UI。
(如果用户在单击 "Save" 按钮后立即移动另一页,我将忽略此处的情况。)
那么,有没有办法让我知道所有异步调用何时完成,然后调用一个方法来更新 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
}