C# 关于Semaphore 信号量的用途以及正确用法

今天说说一个也很好用的互斥锁,主角就是Semaphore
其实Semaphore 是一种用于限制同时访问某一资源或资源池的线程数量的同步机制。它类似于交通信号灯,控制进入某个区域的车辆数量。
以下是 Semaphore 的用途和正确用法的详细说明及示例。

  1. Semaphore 用途
    • 限制资源访问:确保同一时间只有固定数量的线程可以访问某个资源或资源池。
    • 控制并发:用于控制并发线程的数量,防止资源过载。
  2. 正确用法
    Semaphore 的构造函数接受两个参数:
    • 初始计数:当前可用的许可证数量。
    • 最大计数:允许的最大许可证数量。
private static Semaphore semaphore = new Semaphore(3, 3); // 初始计数为 3,最大计数也为 3

直接上代码讲讲以前开发过程中的实战

示例1:限制文件处理线程数量

假设我们有一个文件处理任务,希望同时最多有 3 个线程处理文件。

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
   
   
    private static Semaphore semaphore = new Semaphore(3, 3); // 初始计数为 3,最大计数也为 3

    public static void Main()
    {
   
   
        string[] files = {
   
    "file1.txt", "file2.txt", "file3.txt", "file4.txt", "file5.txt" };

        Task[] tasks = new Task[files.Length];
        for (int i = 0; i < files.Length; i++)
        {
   
   
            string file = files[i];
            tasks[i] = Task.Run(() => ProcessFile(file));
        }

        Task.WaitAll(tasks);
        Console.WriteLine("All files processed.");
    }

    private static void ProcessFile(string file)
    {
   
   
        semaphore.WaitOne(); // 请求一个许可证
        try
        {
   
   
            Console.WriteLine($"Processing {
     
     file} on thread {
     
     Thread.CurrentThread.ManagedThreadId}");
            // 模拟文件处理时间
            Thread.Sleep(1000);
        }
        finally
        {
   
   
            semaphore.Release(); // 释放一个许可证
            Console.WriteLine($"Finished processing {
     
     file} on thread {
     
     Thread.CurrentThread.ManagedThreadId}");
        }
    }
}
  1. 详细说明
    • 创建 Semaphore:new Semaphore(3, 3) 创建一个初始计数为 3,最大计数也为 3 的信号量。
    • 请求许可证:semaphore.WaitOne() 请求一个许可证,如果当前可用许可证数量大于 0,则立即返回;否则,线程将阻塞,直到有许可证可用。
    • 释放许可证:semaphore.Release() 释放一个许可证,增加可用许可证的数量。
    • 异常处理:使用 try…finally(另一话题的文章) 块确保即使在处理过程中发生异常,许可证也能被正确释放。
  2. 其他用途
    • 控制数据库连接池:限制同时打开的数据库连接数量。
    • 控制网络请求:限制同时发送的网络请求数量,防止服务器过载。

示例2:控制数据库连接池

假设我们有一个数据库连接池,希望同时最多有 5 个连接。

using System;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
   
   
    private static Semaphore semaphore = new Semaphore(5, 5); // 初始计数为 5,最大计数也为 5
    private static string connectionString = "YourConnectionStringHere";

    public static void Main()
    {
   
   
        Task[]<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜空晚星灿烂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值