When writing an async function or method, I encountered a problem with accessing data one-by-one, such as starting 100000 async APIs, which could lead to bugs.
Below is a problem example. I expect the result to be “Sum:100000”, but the actual result is “Sum:99995” or other abnormal results.
Example 1:
1 | namespace SemaphoreSlimExample; |
Result:
1 | Sum:99995 |
To fix this problem, I added the SemaphoreSlim to code, and the result always is correct “Sum:100000”.
It helps us lock and limit the asynchronous function’s data to one-by-one.
What is Semaphoreslim:
https://learn.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=net-7.0
Represents a lightweight alternative to Semaphore that limits the number of threads that can access a resource or pool of resources concurrently.
Example2:
1 | namespace SemaphoreSlimExample; |
Result:
1 | Sum:100000 |