若本"单身"是线程安全的在ASP.NET应用程序? [英] Should this "singleton" be thread-safe in an ASP.NET app?

查看:153
本文介绍了若本"单身"是线程安全的在ASP.NET应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,在略微少见的意义上使用单 - 对象作为单个实例像HttpContext.Current可见不同于一般的有一个共享的实例对象

Note that "singleton" used in slightly uncommon sense - "object visible as single instance like HttpContext.Current" unlike normal "object with one shared instance".

我使用一个单独的类型的UserContext 类的对我的asp.net MVC应用。这个类可以让我的用户数据存储为一个强类型的会话对象。我碰到运行此代码审查问题并想知道,如果它是有必要。关注这个应用上下文中的线程安全

I make use of a singleton type of UserContext class for my asp.net MVC applications. This class allows me to store user data as a strongly-typed session object. I ran across this CodeReview question and wondered if it was necessary to be concerned about thread safety in this application context.

下面是我的代码的简化:

Here's a simplification of my code:

public class UserContext
{
    private UserContext()
    {
    }

    public static UserContext Current
    {
        get
        {
            if (HttpContext.Current.Session["UserContext"] == null)
                BuildUserContext();

            return (UserContext)HttpContext.Current.Session["UserContext"];
        }
    }

    private static void BuildUserContext()
    {
        if (!user.Identity.IsAuthenticated) return;

        var uc = new UserContext { IsAuthenticated = true };

        // ...snip...
        // Set up user data

        // Save it into the session
        HttpContext.Current.Session["UserContext"] = uc;
    }


    #region Class members
    public bool IsAuthenticated { get; internal set; }
    public string Name { get; internal set; }
    // ...snip...
    // Other properties

    public void Refresh()
    {
        BuildUserContext();
    }

    public void Flush()
    {
        HttpContext.Current.Session["UserContext"] = null;
    }
    #endregion
}



我没有任何锁定的问题,到目前为止,但现在该网站是不是很高的流量。我应该采取乔恩斯基特的线程安全模式还是IIS管理一下吗?

I haven't had any locking issues so far, but right now the site is not very high traffic. Should I adopt Jon Skeet's thread-safe model or does IIS manage that for me?

推荐答案

访问会议已经线程安全的。

Access the Session is already Thread safe.

在一般只要你在一个线程安全的方式访问您的静态属性的共享状态,你不会有任何问题。

In general as long as you access any shared state in your static properties in a thread-safe manner, you won't have any problems.

这篇关于若本"单身"是线程安全的在ASP.NET应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆