ASP.NET 页面中的静态数据 - 线程安全?

发布于 2024-07-15 19:51:21 字数 373 浏览 4 评论 0原文

这个问题的背景是我需要在(静态)WebMethod 中使用一些用户会话数据。 我创建了一个引用我需要的数据的静态属性,如下所示:

private static UserWebSession UserWebSession
{
    get
    {
        return (UserWebSession)HttpContext.Current.Session["UserWebSession"];
    }
}

然后我可以在页面的静态 WebMethod 中调用它。

我的问题是,这种技术线程安全吗? 或者这个属性的值会随着每个新页面请求而更新 - 换句话说,它将返回最近请求该页面的用户的 UserWebSession ?

The background to this question is that I need to use some user session data in a (static) WebMethod. I have created a static property that references the data I need like so:

private static UserWebSession UserWebSession
{
    get
    {
        return (UserWebSession)HttpContext.Current.Session["UserWebSession"];
    }
}

I can then call this in my page's static WebMethod.

My question is, is this technique thread safe? Or will this property's value be updated with every new page request - in other words, it will return the UserWebSession for the user who most recently requested the page?

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

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

发布评论

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

评论(2

糖粟与秋泊 2024-07-22 19:51:21

没关系 - HttpContext.Current 正是为此类事情而设计的。 您将无法获得先前用户的会话。

不过,它依赖于线程(我相信) - 因此,如果您启动任何额外的后台线程,它们将无法看到当前的上下文。

另请注意,尽管此调用在不会获取错误上下文方面是安全的,但当涉及到您对上下文实际执行的操作时,通常的并发警告适用。

That's fine - HttpContext.Current is designed precisely for this sort of thing. You won't get a previous user's session.

It's dependent on the thread though (I believe) - so if you start any extra background threads, they won't be able to see the current context.

Also be aware that although this call is safe in terms of not getting the wrong context, the normal concurrency caveats apply when it comes to what you actually do with the context.

桃气十足 2024-07-22 19:51:21

我不知道页面方法是否能够访问会话状态。 如果可以的话,那你可能就没事了。 我记得对会话状态的访问是序列化的,因此一次只能有一个请求到达给定的会话。

I don't know that a Page Method is able to access Session state. If it can, then you may be ok. I recall that access to Session state is serialized, so that only one request at a time can arrive for a given session.

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