The cross-thread usage of "HttpContext.Current" property and related things

Posted by smwikipedia on Stack Overflow See other posts from Stack Overflow or by smwikipedia
Published on 2011-11-13T04:07:09Z Indexed on 2012/09/01 3:38 UTC
Read the original article Hit count: 140

Filed under:
|

I read from < Essential ASP.NET with Examples in C# > the following statement:

Another useful property to know about is the static Current property of the HttpContext class. This property always points to the current instance of the HttpContext class for the request being serviced. This can be convenient if you are writing helper classes that will be used from pages or other pipeline classes and may need to access the context for whatever reason. By using the static Current property to retrieve the context, you can avoid passing a reference to it to helper classes. For example, the class shown in Listing 4-1 uses the Current property of the context to access the QueryString and print something to the current response buffer. Note that for this static property to be correctly initialized, the caller must be executing on the original request thread, so if you have spawned additional threads to perform work during a request, you must take care to provide access to the context class yourself.

I am wondering about the root cause of the bold part, and one thing leads to another, here is my thoughts:

We know that a process can have multiple threads. Each of these threads have their own stacks, respectively. These threads also have access to a shared memory area, the heap.

The stack then, as I understand it, is kind of where all the context for that thread is stored. For a thread to access something in the heap it must use a pointer, and the pointer is stored on its stack.

So when we make some cross-thread calls, we must make sure that all the necessary context info is passed from the caller thread's stack to the callee thread's stack.

But I am not quite sure if I made any mistake.

Any comments will be deeply appreciated.

Thanks.

ADD

Here the stack is limited to user stack.

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about multithreading