I need to process data in another thread. There are two ways to do this:
Using a thread loop waiting for an event:
AutoResetEvent e = new AutoResetEvent(false)
Thread t = new Thread(delegate
{
while(true)
{
e.WaitOne();
}
};)
void OnProgramStarted()
{
t.Start();
}
void OnDataReceived()
{
e.Set();
}
Using thread pool:
void ProcessData(object state)
{
}
void OnDataReceived()
{
ThreadPool.QueueUserWorkItem(ProcessData);
}
Which way will be faster?
These tests give mixed results.
My control code:
using System;
using System.Diagnostics;
using System.Threading;
namespace t_event_tpool
{
class Program
{
const int t = 1000000;
static Stopwatch sw = new Stopwatch();
static int q1, q2;
static AutoResetEvent e1 = new AutoResetEvent(false);
static AutoResetEvent done1 = new AutoResetEvent(false);
static Thread thread = new Thread(ThreadProc);
static void ThreadProc(object state)
{
while(true)
{
e1.WaitOne();
q1++;
done1.Set();
}
}
static AutoResetEvent done2 = new AutoResetEvent(false);
static void PoolProc(object state)
{
q2++;
done2.Set();
}
static void TestA()
{
sw.Restart();
for(int i = 0; i < t; i++)
{
e1.Set();
done1.WaitOne();
}
sw.Stop();
Console.WriteLine("a " + sw.ElapsedMilliseconds + "\t" + q1);
}
static void TestB()
{
sw.Restart();
for(int i = 0; i < t; i++)
{
ThreadPool.QueueUserWorkItem(PoolProc, i);
done2.WaitOne();
}
sw.Stop();
Console.WriteLine("b " + sw.ElapsedMilliseconds + "\t" + q2);
}
static void Main(string[] args)
{
thread.IsBackground = true;
thread.Start();
TestA();
TestB();
TestA();
TestB();
TestA();
TestB();
}
}
}
With a low processor load (without other applications) TestB is 2 times faster than TestA. With high CPU utilization by other processes, TestA is faster than TestB.
source
share