如何在 C# 中确保对 Web 服务的并发请求有限

本文关键字:服务 并发 请求 Web 确保 | 更新日期: 2023-09-27 18:37:02

我想确保每秒传输到 Web 服务的并发请求不超过 10 个?。我尝试使用互斥类,但失败了。有人可以给我举个例子吗?

如何在 C# 中确保对 Web 服务的并发请求有限

Mutex 类只有在您要跨进程同步线程时才可以帮助您。
要添加对最大同时运行的线程数的限制,请使用Semaphore类。

简单的概述ы可以在这里找到:

  • 锁 vs 监视器 vs 互斥 vs 信号量
  • 同步基元 (MSDN) 概述

MSDN 示例:

using System;
using System.Threading;
public class Example
{
    // A semaphore that simulates a limited resource pool. 
    // 
    private static Semaphore _pool;
    // A padding interval to make the output more orderly. 
    private static int _padding;
    public static void Main()
    {
        // Create a semaphore that can satisfy up to three 
        // concurrent requests. Use an initial count of zero, 
        // so that the entire semaphore count is initially 
        // owned by the main program thread. 
        //
        _pool = new Semaphore(0, 3);
        // Create and start five numbered threads.  
        // 
        for(int i = 1; i <= 5; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Worker));
            // Start the thread, passing the number. 
            //
            t.Start(i);
        }
        // Wait for half a second, to allow all the 
        // threads to start and to block on the semaphore. 
        //
        Thread.Sleep(500);
        // The main thread starts out holding the entire 
        // semaphore count. Calling Release(3) brings the  
        // semaphore count back to its maximum value, and 
        // allows the waiting threads to enter the semaphore, 
        // up to three at a time. 
        //
        Console.WriteLine("Main thread calls Release(3).");
        _pool.Release(3);
        Console.WriteLine("Main thread exits.");
    }
    private static void Worker(object num)
    {
        // Each worker thread begins by requesting the 
        // semaphore.
        Console.WriteLine("Thread {0} begins " +
            "and waits for the semaphore.", num);
        _pool.WaitOne();
        // A padding interval to make the output more orderly. 
        int padding = Interlocked.Add(ref _padding, 100);
        Console.WriteLine("Thread {0} enters the semaphore.", num);
        // The thread's "work" consists of sleeping for  
        // about a second. Each thread "works" a little 
        // longer, just to make the output more orderly. 
        //
        Thread.Sleep(1000 + padding);
        Console.WriteLine("Thread {0} releases the semaphore.", num);
        Console.WriteLine("Thread {0} previous semaphore count: {1}",
            num, _pool.Release());
    }
}