ASP.NET 中的 ThreadLocal 相当于每个请求变量吗?

发布于 2024-11-05 07:20:10 字数 341 浏览 0 评论 0原文

我在 ASP.NET HttpHandler 中使用 ThreadLocal 变量。我认为这会导致每个请求产生一个新变量。

我的应用程序中有一些奇怪的行为。当 ThreadLocal 变量在 ASP.NET 页面中创建和释放时?

如果 ASP.NET 稍后将同一线程用于另一个请求,会发生什么情况?它是否会产生一个新的 ThreadLocal 变量,或者将使用之前创建的值(与另一个请求一起使用)?

如果在实际释放线程时释放 ThreadLocal 变量,那么我的假设在 ASP.NET 中会失败(因为线程返回到池中并且每个请求都不是唯一的)

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 page?

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你爱我像她 2024-11-12 07:20:10

ASP.NET 可以并且将会在请求之间重用线程 - 事实上,如果内存可用,它会为每个请求使用普通 .NET 线程池中的线程。您可能最好使用会话状态。

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.

内心旳酸楚 2024-11-12 07:20:10

尝试用这个:

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());
        }
    }
}

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());
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文