小编Yev*_*nat的帖子

C#静态类私有字段是否安全?

我有一个从多个线程访问的C#静态类.两个问题:

  1. 在声明初始化字段时,我的私有静态字段是否安全?
  2. 从静态构造函数中创建私有静态字段时,我应该锁定吗?

使用来自不同线程的静态类:

class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 100; i++)
            {
                Task.Run(() =>
                {
                    string name = MyStaticClass.GetValue(9555);
                    //...
                });
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

静态类的选项1:

public static class MyStaticClass
    {
        private static MyClass _myClass = new MyClass();

        public static string GetValue(int key)
        {
            return _myClass.GetValue(key);
        }
    }
Run Code Online (Sandbox Code Playgroud)

静态类的选项2:

public static class MyStaticClass
    {
        private static MyClass _myClass;
        private static object _lockObj = new object();

        static MyStaticClass()
        {
            InitMyClass();
        }

        private …
Run Code Online (Sandbox Code Playgroud)

c# static multithreading private class

7
推荐指数
1
解决办法
753
查看次数

标签 统计

c# ×1

class ×1

multithreading ×1

private ×1

static ×1