C# 多线程启动和管理 单例模式

来源:互联网 发布:大数据综合试验区 编辑:程序博客网 时间:2024/05/22 02:26

1.     

    List<Task> taskList = new List<Task>();

            TaskFactory taskFactory = new TaskFactory();

            taskList.Add(taskFactory.StartNew(() =>
                {

//

                }));

//等待所有线程结束

            Task.WaitAll(taskList.ToArray());

2. 无参

Thread thread = new Thread(new ThreadStart(PlayMusic));
            thread.IsBackground = true;
            thread.Start();

3.有参

Thread thread = new Thread(new ParameterizedThreadStart(setSecond));
            thread.IsBackground = true;
            thread.Start(new Object() {  });

跨线程修改

txty.Invoke((MethodInvoker)delegate
            {
                txty.Text = "";
            });


单例模式

public  class Singleton
    {
        private static object mylock = new object();
        private static Singleton singleton = null;
        private Singleton()
        {
            //首次初始化信息
        }
        public static Singleton CreateInstance()
        {
            if(singleton == null)
            {
                lock(mylock)
                {
                    if(singleton==null)
                    {
                        singleton = new Singleton();
                    }
                }
            }
            return singleton;
        }
    }


    public  class SingletonSecond
    {
        private static SingletonSecond singleton = null;
        private SingletonSecond()
        {
            //首次初始化信息
        }
        static SingletonSecond()
        {
            singleton = new SingletonSecond();
        }
        public static SingletonSecond CreateInstance()
        {
            return singleton;
        }
    }
    public  class SingletonThird
    {
        public static SingletonThird singleton = null;
        private SingletonThird()
        {
            //首次初始化信息
        }
        static SingletonThird()
        {
            singleton = new SingletonThird();
        }
    }
    public  class SingletonThird1
    {
        public static SingletonThird1 singleton = new SingletonThird1();
        private SingletonThird1()
        {
            //首次初始化信息
        }
    }


    public  class SingletonThird2 //非单例 单初始化
    {
        static SingletonThird2()
        {
            //首次初始化信息
        }
    }


原创粉丝点击