C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Quote: This method tells Windows to keep a specific number of idle threads to anticipate new requests. The thread pool does not immediately begin creating new idle threads (Microsoft Docs).
Info: ThreadPool.GetMinThreads accepts two out parameters. It is useful to get these values for diagnostics or for changing the actual values.
Result: The code will display 2, 2 on a dual core machine, but can display 4 on a quad core computer.
C# program that uses SetMinThreads
using System;
using System.Threading;
class Program
{
static void Main()
{
// Get the numbers of minimum threads
int w;
int c;
ThreadPool.GetMinThreads(out w, out c);
// Write the numbers of minimum threads
Console.WriteLine("{0}, {1}",
w,
c);
// Change the numbers of minimum threads
ThreadPool.SetMinThreads(20,
c);
}
}
Here: This benchmark runs tests of bursts of activity with 50 work items each time. It changes the minimum thread setting from 2 to 40.
C# program that benchmarks SetMinThreads
using System;
using System.Threading;
class Program
{
static void Main()
{
// Loop through number of min threads we use
for (int c = 2; c <= 40; c++)
{
// Use AutoResetEvent for thread management
AutoResetEvent[] arr = new AutoResetEvent[50];
for (int i = 0; i < arr.Length; ++i)
{
arr[i] = new AutoResetEvent(false);
}
// Set the number of minimum threads
ThreadPool.SetMinThreads(c, 4);
// Get current time
long t1 = Environment.TickCount;
// Enqueue 50 work items that run the code in this delegate function
for (int i = 0; i < arr.Length; i++)
{
ThreadPool.QueueUserWorkItem(delegate(object o)
{
Thread.Sleep(100);
arr[(int)o].Set(); // Signals completion
}, i);
}
// Wait for all tasks to complete
WaitHandle.WaitAll(arr);
// Write benchmark results
long t2 = Environment.TickCount;
Console.WriteLine("{0},{1}",
c,
t2 - t1);
}
}
}
Note: This benchmark is highly dependent on your machine's configuration. I suggest testing the code yourself.
SleepInfo: Some technical details for this article were contributed by Neil Justice.