开发者

Is ThreadLocal in ASP.NET equivalent to a per request variable?

I use a ThreadLocal variable in an ASP.NET HttpHandler. I assumed it will result in a new variable per request.

I have some strange behavior in my application. When a ThreadLocal variable is created and disposed in an ASP.NET p开发者_如何学JAVAage?

What happens if the same thread is used by ASP.NET later for another request? Does it result in a new ThreadLocal variable or the previously created value (which was used with another request) will be used?

If ThreadLocal variables are disposed when the thread is actually disposed, then my assumption fails with ASP.NET (since threads get back to pool and are not unique per request)


ASP.NET can and will reuse threads between requests- in fact, if memory serves it uses a thread from the normal .NET thread pool for each request. You are probably better off using session state instead.


Try with this:

public class WebRequestLocal<T>
{
    private readonly Func<T> _getter;
    private readonly object _id = new object();

    public WebRequestLocal(Func<T> getter)
    {
        _getter = getter;
    }


    public T Value
    {
        get
        {
            HttpContext httpContext = HttpContext.Current;
            if(httpContext == null)
                throw new Exception("HttpContext unavailable.");

            if (httpContext.Items.Contains(_id))
                return (T)httpContext.Items[_id];


            return (T)(httpContext.Items[_id] = _getter());
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜