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

后端 未结 3 1756
佛祖请我去吃肉
佛祖请我去吃肉 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:15

    I was googling for HTTPContext info some time ago. And I found this:

    http://odetocode.com/articles/112.aspx

    It's about threading and HTTPContext. There is good explanation:

    The CallContext provides a service extremely similar to thread local storage (except CallContext can perform some additional magic during a remoting call). Thread local storage is a concept where each logical thread in an application domain has a unique data slot to keep data specific to itself. Threads do not share the data, and one thread cannot modify the data local to a different thread. ASP.NET, after selecting a thread to execute an incoming request, stores a reference to the current request context in the thread’s local storage. Now, no matter where the thread goes while executing (a business object, a data access object), the context is nearby and easily retrieved.

    Knowing the above we can state the following: if, while processing a request, execution moves to a different thread (via QueueUserWorkItem, or an asynchronous delegate, as two examples), HttpContext.Current will not know how to retrieve the current context, and will return null. You might think one way around the problem would be to pass a reference to the worker thread

    So you have to create reference to your HTTPContext.Current via some variable and this variable will be adressed from other threads you will create in your code.

提交回复
热议问题