Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# singleton类中的线程安全方法_C#_Multithreading - Fatal编程技术网

C# singleton类中的线程安全方法

C# singleton类中的线程安全方法,c#,multithreading,C#,Multithreading,这是一个后续问题 我有以下课程: public class MyLazySingleton { // static holder for instance, need to use lambda to construct since constructor private private static readonly Lazy<MyLazySingleton> _instance = new Lazy<MyLazySingleton>((

这是一个后续问题

我有以下课程:

public class MyLazySingleton
{
    // static holder for instance, need to use lambda to construct since constructor private
    private static readonly Lazy<MyLazySingleton> _instance
        = new Lazy<MyLazySingleton>(() => new MyLazySingleton());

    // private to prevent direct instantiation.
    private MyLazySingleton(string str,int i)
    {
             s_c1 = SingletonClass1.Instance(str);
             s_c2 = SingletonClass2.Instance(str);
             s_c3 = SingletonClass3.Instance(i);
    }

    // accessor for instance
    public static MyLazySingletonInstance
    {
        get
        {
            return _instance.Value;
        }
    }
    public void func1()
    {
        if (s_s1.Measure() || s_c2.Measure())
        {
           c_c3.Do();
        }
    }
       static SingletonClass1 s_c1 = null;
       static SingletonClass2 s_c2 = null;
       static SingletonClass3 s_c3 = null;
}
公共类MyLazySingleton
{
//例如,静态持有者需要使用lambda来构造,因为构造函数是私有的
私有静态只读惰性\u实例
=新的懒惰(()=>新的MyLazySingleton());
//私有以防止直接实例化。
私有MyLazySingleton(字符串str,int i)
{
s_c1=SingletonClass1.Instance(str);
s_c2=SingletonClass2.Instance(str);
s_c3=单例类3.实例(i);
}
//例如访问者
公共静态MyLazySingleStation
{
得到
{
返回_instance.Value;
}
}
公共图书馆1(
{
如果(s|s1.Measure()| s|c2.Measure())
{
c_c3.Do();
}
}
静态单声道Class1 s_c1=null;
静态SingletonClass2 s_c2=null;
静态SingletonClass3 s_c3=null;
}
  • 我开始实现它,让它有一个带参数的构造函数,但不知道如何继续。有什么建议吗
  • 我在前面问题的评论中说func1不是线程安全的。如何使它成为线程安全的?
    MyLazySingleton
    是否定义为懒惰而不是为了线程安全

  • 什么是
    SingletonClass1
    SingletonClass2
    SingletonClass3
    ?为什么要将每个变量的值赋给
    SingletonClass1
    变量?如果有人两次调用MyLazySingletInstance,第二次使用了不同的参数,你会期望发生什么?@JonSkeet-它们是我从dll获得的单例类。@JonSkeet-问题是edited@JonSkeet-只能调用一次(只需参数化)。@Yakov,你读过JonSkeet的C#中的单例指南吗?