Powered by Blogger.

Saturday, March 1, 2014

How to use a Thread Pool class in C#.Net:



A thread pool is a collection of threads that can be used to perform a number of tasks in the background. This leaves the primary thread free to perform other tasks asynchronously.Thread pools are often used in server applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests.

Also check out:

- Increase column size in sql server 2008

- alert() method examples in JavaScript

- Data access block of Microsoft enterprise library 6.0 using inline sql statement

Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task. Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available.

Some of the useful methods to work with Thread Pool  are:

- GetAvail­ableThreads method which returns the num­ber of threads avail­able to you
- Get­MinThreads method returns the num­ber of idle threads the thread pool main­tains in antic­i­pa­tion of new requests
- Get­Max­Threads method returns the max num­ber of thread pool threads that can be active concurrently
- Set­MinThreads method sets the num­ber of idle threads the thread pool main­tains in antic­i­pa­tion of new requests
- Set­Max­Threads method sets the num­ber of thread pool threads that can be active concurrently
- QueueUserWorkItem  Queues a method for execution. The method executes when a thread pool thread becomes available
- WaitCallback representing the method to execute

Example code snippet for threadpool class

using System;
using System.Threading;
public class ThreadPoolExample
{
   public ThreadPoolExample()
   {
      int i;
      ThreadPool.QueueUserWorkItem(new WaitCallback(C1));
      ThreadPool.QueueUserWorkItem(new WaitCallback(C2));
      for(i = 0; i < 10; i++)
      {
         Console.WriteLine("main thread: {0}", i);
         Thread.Sleep(500);
      }
   }
   void C1(object state)
   {
      int i;
      for (i = 0; i < 10; i++)
      {
         Console.WriteLine("  thread1: {0}", i);
         Thread.Sleep(1000);
      }
   }
   void C2(object state)
   {
      int i;
      for (i = 0; i < 10; i++)
      {
         Console.WriteLine("    thread2: {0}", i);
         Thread.Sleep(1500);
      }
   }
   public static void Main()
   {
      ThreadPoolExample tp = new ThreadPoolExample();
   }



0 comments

Post a Comment