Wednesday, February 27, 2013

Threading: 12- ThreadPool

Managed thread pool, provides efficient use of threads with a pool of background threads managed by system.

 

Example Code

using System;
using System.Threading;

// Creating thread pool thread

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        ThreadPool.QueueUserWorkItem(Greet, new object[] { "Bob", "Good Morning" });
        Console.ReadKey();
    }


    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
        Console.WriteLine("\tThread Name: " + Thread.CurrentThread.Name);
        Console.WriteLine("\tThread Id: " + Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("\tIs Background: " + Thread.CurrentThread.IsBackground);
        Console.WriteLine("\tIs ThreadPool Thread: " + Thread.CurrentThread.IsThreadPoolThread);
        Console.WriteLine("\tIs Alive: " + Thread.CurrentThread.IsAlive);
        Console.WriteLine("\tPriority: " + Thread.CurrentThread.Priority);
        Console.WriteLine("\tThread State: " + Thread.CurrentThread.ThreadState);
    }
}

Output

Main Started
Hi Bob, Good Morning!
        Thread Name:
        Thread Id: 11
        Is Background: True
        Is ThreadPool Thread: True
        Is Alive: True
        Priority: Normal
        Thread State: Background

No comments:

Post a Comment