HttpContext.Current null inside async task

寵の児 提交于 2019-11-30 12:18:28

The "task friendly sync context" here applies to the continuation from the await: whatever you do with result, it will have the http-context. It does not, however, relate to task.Start. That relates to the TaskScheduler, not the sync-context.

Basically, by performing this on a worker, you are (in the process, as a consequence) divorcing that worker from the http-context. You must either:

  • get the information you need from the http-context and pass that into the worker, or
  • don't use a worker

Personally, I doubt you're gaining much by pushing this onto a worker. If you really want to go async, the ideal would be for your repo to internally support *Async methods. That requires more than using threads: it usually means architectural changes, for example, using async SQL methods. Something written from the ground up to use async and sync-context-aware continuations (aka await) would automatically preserve things like the http-context.

The important difference here is that an async/await implementation is linear but not continuous, i.e.

 <===(work)==>
                    <===(callback; more work)===>
                                                     <===(another callback)===>

where-as your existing code potentially performs things in parallel, i.e.

<==========(original work)=================>
         <===========(task on worker thread)=============>

The fact that the async/await approach is basically linear makes it far more suitable for access to things like http-context, since it knows that (done right) there will only be one thread at a time accessing it - even if it isn't the same thread end-to-end.

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