Groups | Blog | Home
all groups > asp.net > april 2004 >

asp.net : Are thread-local variables retained after processing?


Steve - DND
4/23/2004 10:51:24 PM
If I declare a property as ThreadStatic, or I use the thread Context to set
values on, will they be retained after a page processes? When a page
finishes, is all data on the thread wiped before it is returned for use by
another page request?

Thanks,
Steve

Steve - DND
4/24/2004 10:47:08 AM
[quoted text, click to view]

That's kind of what I thought, as I didn't see different behavior when
playing with my own thread pools. The problem with using the HttpContext, is
that this needs to work with a business tier of code, which may be used on a
Windows machine as well. I guess I could try and work something where it
would first check for an HttpContext, and if not present, try to use the
thread's CurrentContext. Any other ideas?

Thanks,
Steve

Scott Allen
4/24/2004 11:47:48 AM
If I create a ThreadStatic variable on an ASP.NET thread servicing my
page request, than the ThreadStatic variable will still be around when
the thread finishes processing the request and returns to the free
thread pool.

The ASP.NET runtime will pick the thread out at a later point to
process another request, and the you'll find the ThreadStatic variable
is still around.

If you are looking for a container that will servce just the lifetime
of a single request, try the Items collection of the HttpContext class
(sample: http://odetocode.com/Articles/111.aspx). ASP.NET will ensure
the collection is properly initialized for each request.

I'd be cautious using ThreadStatic variables in ASP.NET. Since the
threads are managed by thread pool I would not have control over the
lifetime of the thread or my TheadStatic object.

HTH,

--
Scott
http://www.OdeToCode.com


On Fri, 23 Apr 2004 22:51:24 -0700, "Steve - DND"
[quoted text, click to view]
Scott Allen
4/24/2004 4:10:11 PM
I think I would abstract away the source of information into another
class/object which could check for an HttpContext. It follows the
'keep it simple' rule and keeps all the Http specific "stuff" in one
place.

--s

On Sat, 24 Apr 2004 10:47:08 -0700, "Steve - DND"
[quoted text, click to view]

--
Scott
Rick Spiewak
4/25/2004 9:48:05 AM
If you want data associated with a page, why not use ViewState? Or, if it's
for the session, Session state?

[quoted text, click to view]

Alvin Bruney [MVP]
4/25/2004 10:53:34 AM
in addition,
this is a good link explain the why behind scott's suggestions
http://www.hanselman.com/blog/PermaLink.aspx?guid=320

--
Regards,
Alvin Bruney
[ASP.NET MVP http://mvp.support.microsoft.com/default.aspx]
Got tidbits? Get it here... http://tinyurl.com/27cok
[quoted text, click to view]

AddThis Social Bookmark Button