net 多线程 学习 08 Semaphore SemaphoreSlim 信号量锁

这种锁的特点就是可以限制进去线程的数量

semaphoreSlim 限制线程数量

限制一个进程中同时可以运行的最多的线程的数量


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Semaphores
{
    class Program
    {
        static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(3); // only allow 3 threads to access the resource
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                new Thread(EnterSemaphore).Start(i + 1); // i+1 indicates the id number of the thread, passed into EnterSemaphore(object id) below
            }
        }

        private static void EnterSemaphore(object id)
        {
            Console.WriteLine(id + " is waiting to be part of the club");
            semaphoreSlim.Wait(); // will make the thread wait IF there are already 3 threads using the resource
            Console.WriteLine(id + " part of the club"); // if the wait is over, then the thread can use the resource
            Thread.Sleep(1000 / (int)id);
            Console.WriteLine(id + " left the club");
        }
    }
}


Semaphore 例子


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SemaphoreDemo
{
    class Program
    {
        static Semaphore seLock = new Semaphore(1, 10);
        static void Main(string[] args)
        {
            //比如开启5个task
            for (int i = 0; i < 5; i++)
            {
                Task.Factory.StartNew(
                    () =>
                {
                    Run();
                });
            }

            Console.Read();
        }
        static int nums = 0;
        static void Run()
        {
            for (int i = 0; i < 100; i++)
            {
                try
                {
                    seLock.WaitOne();
                    Console.WriteLine(nums++);
                    seLock.Release();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {

                }
            }
        }
    }
}



作者:spike

分类: Net

创作时间:2023-06-25

更新时间:2024-12-09

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1