在页面加载上调用异步方法并等待完成执行-C#
c#
我想在我的项目的页面加载事件上调用 web api 方法。但我想等待函数“GetSelectedTaskDetails”的执行完成。这样我就可以使用 DataRow 行中的值进行管理。你能建议我如何实现这一目标吗?
private DataRow row;
protected void Page_Load(object sender, EventArgs e)
{
GetSelectedTaskDetails(Id);
//other codes
}
private async void GetSelectedTaskDetails(int? selected_task_id)
{
try
{
url = baseUrl + "GetSelectedTaskDetails?task_id=" + selected_task_id;
using (var objClient = new HttpClient())
{
using (var response = await objClient.GetAsync(url))
{
if ((int)response.StatusCode == 401)//unauthorised or token expired
{
Response.Redirect("Default.aspx");
}
if (response.IsSuccessStatusCode)
{
var GetResponse = await response.Content.ReadAsStringAsync();
DataTable dt = JsonConvert.DeserializeObject<DataTable>(GetResponse);
if (dt.Rows.Count == 1)
{
row = dt.Rows[0];
}
}
}
}
}
catch (Exception ex)
{
var message = new JavaScriptSerializer().Serialize(ex.Message.ToString());
var script = string.Format("alert({0});", message);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", script, true);
}
}
回答
您应该避免async void- 它用于事件处理程序。所以GetSelectedTaskDetails应该是async Task而不是async void. 一旦GetSelectedTaskDetails正确返回 a Task,您可以await在您的Page_Load:
protected async void Page_Load(object sender, EventArgs e)
{
await GetSelectedTaskDetails(Id);
...
}
请注意,为了async在 ASP.NET pre-Core 上正常工作,您需要设置Page.Async为true并确保httpRuntime@targetFramework设置为 4.5 或更高版本web.config
- @MarcGravell: Yup, that's why there's three parts to the answer. `async void` is allowed for `Page_Load` - *if* you've set `Page.Async` to `true` *and* enabled the non-legacy ASP.NET `SynchronizationContext` (e.g., via `httpRuntime.targetFramework`). Unfortunately convoluted, yet an impressive level of support for a technology as old as WebForms.