- using System;
- using System.Threading;
- namespace Test
- {
- class Program
- {
- const int waitTime = 10000;
- static void Main(string[] args)
- {
- for (int i = 0; i < 10; i++ )
- ThreadPool.QueueUserWorkItem( TestProc, i);
- Console.ReadKey();
- }
- static void TestProc(object stateInfo)
- {
- Console.WriteLine("Item number #{0} at {1}", (int)stateInfo, DateTime.Now);
- Thread.Sleep(waitTime);
- }
- }
- }
The problem is that thread pool waits around 500 ms before allocating a new thread.
You may solve it by pre-specifying a minimal amount of threads in your application:
ThreadPool.SetMinThreads(20, 200);
3 comments:
I am not sure what you did is right. try this one.
class Program
{
const int waitTime = 10000;
static void Main(string[] args)
{
ManualResetEvent[] items = new ManualResetEvent[10];
for (int i = 0; i < 10; i++)
{
items.Add(new ManualResetEvent(false));
}
Console.Out.WriteLine(DateTime.Now.ToLongTimeString());
foreach(ManualResetEvent context in items)
{
ThreadPool.QueueUserWorkItem(TestProc, context);
}
foreach (ManualResetEvent context in items)
{
context.WaitOne();
}
Console.Out.WriteLine(DateTime.Now.ToLongTimeString());
}
static void TestProc(object stateInfo)
{
Console.WriteLine(DateTime.Now);
Thread.Sleep(waitTime);
((ManualResetEvent)stateInfo).Set();
}
}
Tried it - same result - takes a time until you get into the thread function. It's just optimization of .NET. Use ThreadPool.SetMinThreads()
Thank you for the explanation Alex.
Best regards
Post a Comment