C# 高级特性(三)多线程

1,锁:控制多线程并发操作时,线程安全问题。

举例:

static bool done;   //线程是否完成标识
static object locker = new object(); //线程锁

static void Main(string[] args)
 {
            Thread thread = new Thread(Test); // 打开多线程运行Test()
            thread.Start();
            thread.Name = "thread";
            Test();   // 主线程运行Test()

            Console.ReadKey();
 }

 static void Test()
{
            lock (locker)
            {
                if (!done)
                {
                    Thread.Sleep(500); // Doing something.
                    Console.WriteLine("Done. Thread name:" + Thread.CurrentThread.Name);
                    done = true;
                }
            }
}

结果:Done. Thread name:thread

上例中有主副两个线程,理论上来讲主线程和副线程不分先后都有可能调用Test方法,实际情况是副现场调用先调用Test方法,进程锁定,主进程无法调用。

2,ManualResetEvent实现进程信号机制

        static object locker = new object(); 
        static ManualResetEvent signal = new ManualResetEvent(false);
        static void Main(string[] args)
        {
            Thread thread = new Thread(Go);
            thread.Start();


            bool runThread = true;
            while (runThread)
            {
                string input = Console.ReadLine();
                if (input.Trim().ToLower() == "stop")
                {
                    Console.WriteLine("线程已停止运行...");
                    signal.Reset();
                }
                else if (input.Trim().ToLower() == "run")
                {
                    Console.WriteLine("线程开启运行...");
                    signal.Set();
                }
                else if (input.Trim().ToLower() == "exit")
                {
                    runThread = false;
                }
            }
        }

      static void Go()
        {
            lock (locker)
            {
                while (true)
                {
                    Console.WriteLine("Waiting for signal...");
                    signal.WaitOne();
                    Console.WriteLine("Got signal!");
                    Thread.Sleep(5000);
                }
            }
        }

当输入stop时进行暂停等待信号,输入run获得进行信号开始运行。

猜你喜欢

转载自blog.csdn.net/weixin_42339460/article/details/81185003