Why is ASP.NET HttpContext.Current not set when starting a task with current synchronization context

后端 未结 3 1751
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 01:58

I was playing around with asynchronous features of .NET a little bit and came up with a situation that I couldn\'t really explain. When executing the following code inside a syn

3条回答
  •  醉酒成梦
    2021-02-04 02:41

    Your results are odd - are you sure there's nothing else going on?


    Your first example ( with Task ) only works because Task.Wait() can run the task body "inline".

    If you put a breakpoint in the task lambda and look at the call stack, you will see that the lambda is being called from inside the Task.Wait() method - there is no concurrency. Since the task is being executed with just normal synchronous method calls, HttpContext.Current must return the same value as it would from anywhere else in your controller method.


    Your second example ( with SynchronizationContext.Post ) will deadlock and your lambda will never run.

    This is because you are using an AutoResetEvent, which doesn't "know" anything about your Post. The call to WaitOne() will block the thread until the AutoResetEvent is Set. At the same time, the SynchronizationContext is waiting for the thread to be free in order to run the lambda.

    Since the thread is blocked in WaitOne, the posted lambda will never execute, which means the AutoResetEvent will never be set, which means the WaitOne will never be satisfied. This is a deadlock.

提交回复
热议问题