Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of checking the number of threads in a thredpool
[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
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
Trace.WriteLine(message: $"Decrease CountDown, current count: {cde.CurrentCount}");
// Signal that at least one thread is executed.
// ensure that at least one thread was created
// Decrease the counter (as it was initialized with the value 1).
// Wait until the counter is zero.
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
You can’t perform that action at this time.