WebApi equivalent for HttpContext.Items with Dependency Injection

末鹿安然 提交于 2019-12-04 07:31:19

using TPL calls, not async/await due to some interface that needs to be matched

I recommend you take another look at async and await. It is possible to use async for your part of the implementation and have it interoperate with other asynchronous APIs.

That said, if you want to preserve HttpContext.Current (as well as culture, etc.), then the key is SynchronizationContext. I have an MSDN article on that type that you may find helpful. Since your code is using TPL, you would probably want to capture the request context into a task scheduler:

var requestContext = TaskScheduler.FromCurrentSynchronizationContext();

and then use that to schedule your task continuations.

The other important aspect of asynchronous work on ASP.NET is to ensure that the runtime is aware of your asynchronous work. You can do this by calling AsyncOperationManager.CreateOperation to register asynchronous work before it starts and AsyncOperation.OperationCompleted to notify the runtime that the asynchronous work has completed. Alternatively, you can capture the SynchronizationContext.Current and call SynchronizationContext.OperationStarted and SynchronizationContext.OperationCompleted yourself.

Again, take another look at async and await and see if it's at all possible to use them; they'll take care of all the gritty details like this for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!