Posting an Asynchronous Operation on Thread Pool

How to queue an operation on thread pool and how to utilize thread pool for better performance

Category: Multithreading Tags: C#


        In previous article we learnt about thread pool. In this article we are going to see how to post an operation on thread pool queue. If thread pool has any thread free it will reuse that to perform posted operation else thread pool will create new thread for that.


    First we will create a method which accepts state as parameter:

static void DemoOperation(object state)
    Console.WriteLine("Demo Started, Thread ID: " + Thread.CurrentThread.ManagedThreadId);
    Console.WriteLine("State: {0}", state == null ? "(null)" : state);
    Console.WriteLine("Async Completed");

Above method prints thread id and state of thread, now we are going to post this operation on thread pool multiple times as well as we will post some other operations using lambda expressions in Main thread:

static void Main(string[] args)
    //Async Operation1
    ThreadPool.QueueUserWorkItem(DemoOperation, "Async Operation1");
    //Async Operation2
    ThreadPool.QueueUserWorkItem(DemoOperation, "Async Operation2");
    //lambda version of posting an operation
    //Lambda State1
    ThreadPool.QueueUserWorkItem(state =>
        Console.WriteLine("This Operation State: {0}", state);
        Console.WriteLine("Thread ID: {0}", Thread.CurrentThread.ManagedThreadId);
    }, "Lambda State1");

    //Lambda State2
    ThreadPool.QueueUserWorkItem(_ =>
        Console.WriteLine("This Operation State: {0}", "Lambda State2");
        Console.WriteLine("Thread ID: {0}", Thread.CurrentThread.ManagedThreadId);


Above code is posting operation using QueueUserWorkItem method. First we post Async Operation1 and Async Operation2 then Lambda State1 and we wait for 2 seconds. Before we post Lambda State2, Async Operation1 and Async Operation2 are already finished execution so Lambda State2 might reuse the thread freed by Async Operation1. See output below:

Demo Started, Thread ID: 10
State: Async Operation1
Demo Started, Thread ID: 11
State: Async Operation2
This Operation State: Lambda State1
Thread ID: 12
Async Completed
Async Completed
This Operation State: Lambda State2
Thread ID: 10

Above output you can see Async Operation1 had thread id 10 and this thread completed execution before Lambda State2 started so Lambda State2 executed on same thread(thread id 10) instead of creating new thread.

Like 0 People
Last modified on 11 October 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 165
Questions: 16
Given Best Solutions: 16 *


No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User