【发布时间】:2013-12-02 08:06:51
【问题描述】:
我有一个使用 BCL async/await 包的 MVC 4.0 站点。 为了在初始线程和后续线程(等待之后)中保留 HttpContext,我首先创建了一个引用上下文的闭包,如下所示:
public async Task<ViewResult> GetCustomer(int id)
{
var ctx = HttpContext.Current;
ctx["test"] = "test";
await DoSomeLongRunningIO();
var test = ctx["test"];
//do other things with context
return View();
}
但是,我需要在等待之后调用各种服务。这些遗留服务直接调用 HttpContext.Current。 所以我用下面的代码解决了这个问题,这似乎是一种确保这些服务仍然按预期工作的简单方法。
public async Task<ViewResult> GetCustomer(int id)
{
var ctx = HttpContext.Current;
await DoSomeLongRunningIO();
HttpContext.Current = ctx;
//call other services which use static references to httpcontext
return View();
}
这确实有效,但我一直在阅读this answer that suggests it is a bad idea:
- 这是一个坏主意,如果是,为什么它比第一个示例更糟糕?
感谢您的宝贵时间。
【问题讨论】:
标签: asp.net-mvc-4 async-await c#-5.0