Wednesday, June 17, 2009

C#: Simple Threading Example Using ThreadPool

With machines now being sold with multiple cores, why should your application be using only one? Harness the full potential of the processor(s) and make your app shine!

Threading seems so complicated, it really isn’t. Today, I’ll provide an example of the simplest thread code you’ve ever seen. In fact, it’s so simple, here it is:

class TheTest
{
public void Go()
{
for (int i = 0; i < 100; i++)
{
WaitCallback wcb = new WaitCallback(this.DoWork);
ThreadPool.QueueUserWorkItem(wcb, i);
}
Console.ReadLine();
}

public void DoWork(object state)
{
int i = (int)state;
Console.WriteLine(string.Format("{0:d3} started",i));
Thread.Sleep(500);
Console.WriteLine(string.Format("{0:d3} done", i));
}
}

Create a new instance of the TheTest class, call go. You’ll see 100 threads get created and do work. You can pass in anything you want for the state. That’s a very good place to put your “unit of work” that the thread must work on. Just make sure you add a using clause for System.Threading.

Of course, this post doesn’t touch on any locking or blocking issues, I’ll do that later. But for now, why not multithread?

2 comments: