Home >Backend Development >C++ >How Can SemaphoreSlim Control Concurrency for Async Operations in .NET?

How Can SemaphoreSlim Control Concurrency for Async Operations in .NET?

Linda Hamilton
Linda HamiltonOriginal
2025-02-01 21:01:14415browse

How Can SemaphoreSlim Control Concurrency for Async Operations in .NET?

Limiting Concurrent Asynchronous Tasks in .NET

Handling numerous concurrent asynchronous operations requires careful management to prevent system overload. The example code initiates over 1000 web requests simultaneously, a potential recipe for resource exhaustion.

The SemaphoreSlim class, introduced in .NET 4.5 Beta, provides an elegant solution for controlling concurrency with its WaitAsync method. This allows for efficient asynchronous operation throttling:

<code class="language-csharp">public async Task MyOuterMethod()
{
    var semaphore = new SemaphoreSlim(20); // Maximum 20 concurrent requests
    var tasks = new List<Task>();

    foreach (var url in urls)
    {
        await semaphore.WaitAsync(); // Acquire a permit

        tasks.Add(Task.Run(async () =>
        {
            try
            {
                using (var client = new HttpClient()) // Use using statement for proper disposal
                {
                    var html = await client.GetStringAsync(url);
                    // Process the result
                }
            }
            finally
            {
                semaphore.Release(); // Release the permit
            }
        }));
    }

    await Task.WhenAll(tasks); // Wait for all tasks to complete
}</code>

By initializing SemaphoreSlim with a count of 20, we ensure a maximum of 20 simultaneous requests. WaitAsync pauses execution until a permit is available. Crucially, the finally block guarantees the permit is released, even if exceptions occur. The using statement ensures proper disposal of the HttpClient.

While alternative approaches, such as custom task schedulers, exist, SemaphoreSlim offers a concise and effective method for managing asynchronous concurrency. The MSDN documentation provides further details on these alternative techniques.

The above is the detailed content of How Can SemaphoreSlim Control Concurrency for Async Operations in .NET?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn