静态字段是否安全

时间:2014-11-17 15:17:59

标签: c# wcf static thread-safety static-members

我们在抽象类中有一个静态字段

摘要类: -

public abstract class BaseController
{

 private static string a;
 private static string b;

 protected abstract SomeArray[] DoSomeThing();

}

派生类

public class Controller1:BaseController
{

      protected override SomeArray[] DoSomthing()
      {
        //////
        In this method we are setting the static variables with different values
      }

}

我们还有一个正在启动线程的类

public class SomeClass 
{

  public SomeClass()
  {
    \\ we are setting the controller we want to call, i mean to decide which base class to call 
  }

   public void Run()
   {
     Thread t  = new Thread(StartThread);
    t.Start();

   }

  public void StartThread()
  {
     _controller.DoSomeThing();
  }

}

所有上述服务都在WCF服务中,同一个客户端尝试多次调用,这意味着我们同时运行多个线程,我们已经看到了我们正在设置静态变量并使用它的问题某些数据库更新过程有时会出现错误的值

我已经阅读了一些博客,其中说静态字段不是线程安全的,有些正文可以帮助我理解代码中可能出错的内容以及为什么我们将一些不正确的值传递给数据库。

1 个答案:

答案 0 :(得分:0)

根据定义,静态字段或成员在该类的所有实例之间共享,只有该字段或成员的一个实例存在;因此,它不是线程安全的。

您有两个选项,要么将访问权限(基本上,使用Monitor类)与该字段同步,要么在该字段上使用ThreadStaticAttribute。

但是,我建议重新组织您的类层次结构,以便每个类都有自己的字段或成员实例。

请注意,如果有多个线程在类Controller的同一个实例上工作,那么我们会回到同样的问题,您应该同步对该实例字段的访问。

祝你好运