关于异步操作后的 c#:HttpContext.Current.Items
HttpContext.Current.Items after an Async operation
考虑以下 ASP.NET Web API 委托处理程序:
|
public class MyHandler : DelegatingHandler
{ protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var guid = Guid.NewGuid(); HttpContext.Current.Items["foo"] = guid; // An Async operation //All code from this point is not gauranteed to run on the same thread that started the handler var restoredGuid = (Guid)HttpContext.Current.Items["foo"]; //Is this gauranteed to be true return result; |
上面的例子是在一个委托处理程序中,我试图解决的同样的问题也适用于控制器、业务对象等。
我最终试图在每个 HTTP 请求的各种对象之间提供一些简单的内存共享状态
据我了解,在异步操作期间,最初运行该操作的 ASP.NET 线程将返回到线程池,并且在异步操作完成后,可能会使用不同的线程来完成请求。
这会影响
我知道使用
由于我完全同意的原因,这些天来更广泛的社区
与...我只是在帮助某人摆脱困境。
将此数据存储在
非常感谢
相关讨论
- 这可能会有所帮助:stackoverflow.com/questions/17261571/...
- 这个:stackoverflow.com/questions/15196556/…
- 嗨,杰森,这些问题;虽然相似;不完全一样。不过谢谢。
- 啊,好的:)不用担心。
-
HttpContext 将被保留,但延续线程可能不同。 AspNetSynchronizationContext 将管理上下文。
As I understand it during Async operations the ASP.NET thread originally running the operation is returned to the thread pool and a different thread may be used to finish the request after the Async operation has completed.
没错。但是让我们花一分钟时间来谈谈 ASP.NET 上的
的
如果您的 web.config 没有这些条目之一,则
Does this affect the HttpContext.Current.Items collection? Is an item that was in the Items collection guaranteed to be there when the Request resumes?
另一种可能是
几周前,我在服务器端的
相关讨论
- 谢谢斯蒂芬,很好的回应。
长话短说,通常应该如此。除非您使用的是
或者尝试在您的应用中添加此设置。
|
</appSettings>
|
更新
注意!!
最初我把假的。但它必须是真实的,这样上下文才能流动。