我理解await会等待一个任务(可等待对象)完成,但实际上这是什么意思我有点糊涂。
不起作用的代码:
public async override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response.Content != null)
{
var responseContent = await actionExecutedContext.Response.Content.ReadAsStringAsync();
DoSomething(responseContent);
}
}
能够正常工作的代码:does
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response.Content != null)
{
var responseContent = actionExecutedContext.Response.Content.ReadAsStringAsync().ContinueWith(
task =>
{
DoSomething(task.Result);
});
}
}
显然,错误信息An asynchronous module or handler completed while an asynchronous operation was still pending.告诉我,没有等待异步调用完成,而是"主"线程继续执行。我期望该线程会继续执行,但不是在当前方法内。我认为该线程将返回到asp.net堆栈中进行其他工作,并在await asyncOperation()操作完成后返回。
我在其他地方也使用了 await(例如等待 Web 服务响应),但在任何地方都没有遇到类似的问题。我想知道为什么 IActionFilterAttribute 的行为不同。实际上,我的 Web 服务调用可能比读取响应内容到字符串中需要更长的时间。
有人可以说明一下吗?我觉得我可能没有理解这个概念。
AsyncActionFilterAttribute
并实现IActionFilter.ExecuteActionFilterAsync
。 - Stephen Cleary