静态成员变量和线程安全 [英] Static member variable and thread safety

查看:312
本文介绍了静态成员变量和线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个ASP.NET MVC应用程序。

我有一个视图模型类而我试图保持一个计数,以产生div编号这是在一个视图中使用:

 公共类视图模型{    私有静态UINT instanceCount;
    私人只读UINT ID;    公共视图模型(){
        ID = instanceCount ++;
    }    公共UINT DIVID
    {
        {返回ID; }
    }
}

我是正确的思维递增和在Web应用程序分配的静态成员不是线程安全的,因而不是安全?

什么是使这一安全的最佳方式?

感谢。


解决方案

  

我是正确的思维递增和在Web应用程序分配的静态成员不是线程安全的,因而不是安全?


是的,你是正确的,以为这一点。


  

什么是使这一安全的最佳方式?


通过同步访问:

 公共类视图模型
{
    私有静态UINT instanceCount;
    私人只读UINT ID;
    私人静态对象_syncRoot =新的对象();    公共视图模型()
    {
        锁定(_syncRoot)
        {
            ID = instanceCount ++;
        }
    }    公共UINT DIVID
    {
        {返回ID; }
    }
}

或者干脆使用的Guid

 公共类视图模型
{
    公共视图模型
    {
        DIVID =的String.Format(ID_ {0},Guid.NewGuid());
    }    公共字符串DIVID {搞定;私人集; }
}

I am working on an ASP.NET MVC application.

I have a ViewModel class for which I am trying to maintain a count in order to generate div ids which are used in a view:

public class ViewModel {

    private static uint instanceCount;
    private readonly uint id;

    public ViewModel(){
        id = instanceCount++;
    }

    public uint DivId
    {
        get { return id; }
    }
}

Am I correct in thinking incrementing and assigning the static member is not threadsafe and thus not safe in a web application?

What is the best way to make this safe?

Thanks.

解决方案

Am I correct in thinking incrementing and assigning the static member is not threadsafe and thus not safe in a web application?

Yes, you are correct into thinking this.

What is the best way to make this safe?

By synchronizing the access:

public class ViewModel
{
    private static uint instanceCount;
    private readonly uint id;
    private static object _syncRoot = new object();

    public ViewModel()
    {
        lock(_syncRoot)
        {
            id = instanceCount++;
        }
    }

    public uint DivId
    {
        get { return id; }
    }
}

or simply use a Guid:

public class ViewModel
{
    public ViewModel
    {
        DivId = string.Format("id_{0}", Guid.NewGuid());
    }

    public string DivId { get; private set; }
}

这篇关于静态成员变量和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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