Skip to content

Instantly share code, notes, and snippets.

@liorksh
Created April 25, 2020 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liorksh/ec709a40ba8205c67df7d5950716bfcf to your computer and use it in GitHub Desktop.
Save liorksh/ec709a40ba8205c67df7d5950716bfcf to your computer and use it in GitHub Desktop.
Example of checking the number of threads in a thredpool
[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