HttpContext.Current null inside async task

前端 未结 1 1907
太阳男子
太阳男子 2021-01-02 02:12

I have a method that uses a repository (userRepo):

    public override Task CreateLocalUserAsync(IUser user, string passwo         


        
相关标签:
1条回答
  • 2021-01-02 02:48

    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.

    0 讨论(0)
提交回复
热议问题