-
-
Save liorksh/ec709a40ba8205c67df7d5950716bfcf to your computer and use it in GitHub Desktop.
Example of checking the number of threads in a thredpool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Theory] | |
[InlineData(1500, 300)] | |
[InlineData(1200, 160)] | |
public void ThreadPoolWithCounter(int booksAllowance, int threadsToRun) | |
{ | |
// Initialize counter with 1, otherwise, the AddCount method will throw an error (the counter is signaled and cannot be incremented). | |
using (CountdownEvent cde = new CountdownEvent(1)) | |
{ | |
ManualResetEvent manualResetEvent = new ManualResetEvent(false); | |
LibraryAccount account = new LibraryAccount(booksAllowance: booksAllowance); | |
for (int i = 0; i < threadsToRun; i++) | |
{ | |
bool enqueued = ThreadPool.QueueUserWorkItem(delegate | |
{ | |
// Increase the counter | |
cde.AddCount(); | |
Trace.WriteLine(message: $"Increase CountDown, current count: {cde.CurrentCount}"); | |
// Execute the business logic: a thread-safe withdraw books (implements lock internally) | |
account.WithdrawBooksWithExecuterName(10, "Thread_" + DateTime.Now.Ticks); | |
// Decrease the counter | |
cde.Signal(); | |
Trace.WriteLine(message: $"Decrease CountDown, current count: {cde.CurrentCount}"); | |
// Signal that at least one thread is executed. | |
manualResetEvent.Set(); | |
}); | |
} | |
// ensure that at least one thread was created | |
manualResetEvent.WaitOne(); | |
// Decrease the counter (as it was initialized with the value 1). | |
cde.Signal(); | |
// Wait until the counter is zero. | |
cde.Wait(); | |
Trace.WriteLine(message: $"All threads are finished, current count: {cde.CurrentCount}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment