任务同步三

Semaphore类:信号量非常类似于互斥,其区别是,信号量可以同时由多个线程使用。信号量是一种计数的互斥锁定。使用信号量可以定义允许同时访问受旗语锁定保护的资源的线程个数。如果需要限制可以访问可用资源的线程数,信号量就很有用。

        static void Main(string[] args)
        {
            int semapCount = 3;
            var semaphore = new SemaphoreSlim(semapCount, semapCount);
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Task[] tasks = new Task[5];
            for (int i = 0; i < tasks.Length; i++)
            {
                tasks[i] = Task.Run(() => { Taskmain(semaphore); });
            }
            Task.WaitAll(tasks);
            sw.Stop();
            var times = sw.Elapsed.TotalSeconds;
            Console.WriteLine("所消耗时间:" + times);
            Console.ReadLine();
        }
        public static void Taskmain(SemaphoreSlim semaphore)
        {
            bool isCompleted = false;
            while (!isCompleted)
            {
                if (semaphore.Wait(600))
                {
                    try
                    {
                        Console.WriteLine($"任务{Task.CurrentId}锁定信号量");
                        Task.Delay(2000).Wait();
                    }
                    finally
                    {
                        Console.WriteLine($"任务{Task.CurrentId}释放信号量");
                        semaphore.Release();
                        isCompleted = true;
                    }
                }
                else
                {
                    Console.WriteLine($"任务{Task.CurrentId}超时;再次等待");
                }
            }
        }

下一章阐述events类

猜你喜欢

转载自blog.csdn.net/qq_31975127/article/details/86526158