semaphoreslim
时间: 2024-02-04 07:02:32 浏览: 84
SemaphoreSlim is a synchronization primitive in C# that allows controlling access to a limited resource. It is similar to the traditional semaphore, but with a lighter weight and more efficient implementation.
With SemaphoreSlim, you can limit the number of concurrent threads that can access a resource. It provides methods like `Wait` and `Release` to control the acquisition and release of the semaphore.
Here's an example to illustrate its usage:
```csharp
SemaphoreSlim semaphore = new SemaphoreSlim(3); // Limiting to 3 concurrent threads
async Task AccessResource()
{
await semaphore.WaitAsync(); // Acquire the semaphore
try
{
// Access the limited resource here
}
finally
{
semaphore.Release(); // Release the semaphore
}
}
// Spawn multiple threads to access the resource concurrently
Task[] tasks = new Task[5];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = AccessResource();
}
await Task.WhenAll(tasks);
```
In this example, we create a SemaphoreSlim with a maximum count of 3, meaning only 3 threads can access the limited resource simultaneously. The `WaitAsync` method is used to acquire the semaphore, and the `Release` method is used to release it after accessing the resource.
Using SemaphoreSlim can help control access to shared resources, preventing issues like race conditions and excessive resource utilization.