Tuesday, October 11, 2011

Thread Pooling work items in C#

Sometimes you want to perform a work item in another thread but not go through the hassle to create a new thread. A good way to solve the problem is to use the ThreadPool.
using System.Threading;
 
namespace dsc.tools
{
    public class ThreadPooling
    {
        public void StartWorkItem()
        {
            ThreadPool.QueueUserWorkItem(context =>
            {
                // do stuff here
            });
            // or
            ThreadPool.QueueUserWorkItem(DoWork);
        }
 
        private void DoWork(object context)
        {
            // do stuff here
        }
    }
}