ASP.NET MVC 4异步子操作 [英] ASP.NET MVC 4 async child action

查看:138
本文介绍了ASP.NET MVC 4异步子操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC应用程序4针对.NET 4.5。我们的一个孩子的行动进行调用到Web服务使用的HttpClient。

I have an ASP.NET MVC 4 application targeting .NET 4.5. One of our child actions makes a call out to a web service using HttpClient.

由于我们阻塞IO等待HttpClient的响应,它使感很大转换的code到异步/的await格局。然而,当MVC 4尝试执行该子操作,我们得到了以下错误消息:

Since we're blocking on IO waiting for the HttpClient response, it makes a great deal of sense to convert the code to the async/await pattern. However, when MVC 4 attempts to execute the child action, we get the following error message:

HttpServerUtility.Execute阻塞等待异步操作完成。

HttpServerUtility.Execute blocked while waiting for an asynchronous operation to complete.

乍一看,似乎一个孩子的行动中,就好像MVC 4不支持异步/等待。剩下的唯一选择是采用同步code运行,并强制对异步任务等待。

At first glance, it appears as though MVC 4 does not support async/await within a child action. The only remaining option is to run using synchronous code and force a "Wait" on the async task.

大家都知道,在一个ASP.NET上下文中的异步任务触摸。结果或.Wait()会立即导致死锁。我的异步逻辑被包裹在一个类库,所以我不能用等待blah.ConfigureAwait(假)的把戏。请记住,标注异步对孩子的动作和使用的await导致一个错误,并且prevents我从配置的await。

As we all know, touching .Result or .Wait() on an async task in an ASP.NET context will cause an immediate deadlock. My async logic is wrapped in a class library, so I can't use the "await blah.ConfigureAwait(false)" trick. Remember, tagging "async" on the child action and using await causes an error, and that prevents me from configuring the await.

我画成在这一点上一个角落里。有的方式来消耗在MVC 4子操作异步方法?好像没有一个解决方法平出错误。

I'm painted into a corner at this point. Is there any way to consume async methods in an MVC 4 child action? Seems like a flat out bug with no workarounds.

推荐答案

有仍然是不MVC的部分异步 - 友好;我希望这些将在今后得到解决。请不要为此创建连接或UserVoice的问题。

There are still parts of MVC that aren't async-friendly; I hope these will be addressed in the future. Please do create a Connect or UserVoice issue for this.

我的异步逻辑被包裹在一个类库,所以我不能用等待blah.ConfigureAwait(假)的把戏。

My async logic is wrapped in a class library, so I can't use the "await blah.ConfigureAwait(false)" trick.

您也许的补充 ConfigureAwait(假)来在你的类库调用(如果可以的话)。

You probably should add ConfigureAwait(false) to the calls in your class library (if you can).

您也可以砍了一个替代的解决方案。 如果您的类库方法不需要ASP.NET的情况下,那么你可以有一个线程池线程执行(一)等着你:

You could also hack up an alternate solution. If your class library method doesn't need the ASP.NET context, then you could have a thread pool thread do the (a)waiting for you:

try
{
    var result = Task.Run(async () => { await MyHttpRequest(...); }).Result;
}
catch (AggregateException ex) { ... }

的效果类似于 ConfigureAwait(假):因为 MyHtt prequest 在一个线程池中运行情况下,它不会尝试它完成时进入ASP.NET环境。

The effect is similar to ConfigureAwait(false): since MyHttpRequest runs in a thread pool context, it will not attempt to enter the ASP.NET context when it completes.

这篇关于ASP.NET MVC 4异步子操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆