Click here to Skip to main content
12,450,568 members (49,911 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

6.2K views
9 bookmarked
Posted

Thread Pooling in C# – Asynchronous Delegates

, 18 Feb 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Thread Pooling in C# – Asynchronous Delegates

Introduction

ThreadPool.QueueUserWorkItem does not provide an easy way to pass more than one typed parameter and receive the result back from a thread after it has finished executing. Asynchronous delegate solves this limitation, allowing any number of typed arguments to be passed in both directions. Furthermore, un-handled exceptions on asynchronous delegates are conveniently rethrown on the original thread (or more accurately, the thread that calls EndInvoke), and so they don’t need explicit handling.

How to Use Asynchronous Delegates

using System;
using System.Threading;

namespace TestConsole
{
    class Program
    {
        public static void Main(string[] args)
        {
            Func<string, int, string > method = DoLongTask;
            IAsyncResult doLongTaskResult1 = method.BeginInvoke("value1", 1234, null, null);
            IAsyncResult doLongTaskResult2 = method.BeginInvoke("value1", 1234, DoLongTaskCompleted, method);
            // Do other work in parallel...
            string result = method.EndInvoke(doLongTaskResult1);
            Console.WriteLine("Status of DoLongTask is : " + result);
            Console.WriteLine("Main thread ends");
            Console.ReadKey();
        }

        public static string DoLongTask(string param1, int param2)
        {
            Console.WriteLine("Thread is background : {0}", Thread.CurrentThread.IsBackground);
            Console.WriteLine("Input parameter : {0} and {1}", param1, param2);
            return "Success";
        }

        public static void DoLongTaskCompleted(IAsyncResult asyncResult)
        {
            var target = (Func<string, int, string>) asyncResult.AsyncState;
            var result = target.EndInvoke(asyncResult);
            Console.WriteLine("DoLongWork has completed and result is {0}", result);
        }
    }
}

BeginInvoke returns immediately to the caller without waiting for the asynchronous call to complete. You can perform other activities in parallel while the pooled thread is working. When you need the results, simply call EndInvoke on the delegate, passing in the saved IAsyncResult object.

When we call EndInvoke, it waits for the asynchronous delegate to finish executing. It receives the return value (as well as any ref or out parameters). It throws any unhandled exception back to the calling thread.

If you need to call some method after asynchronous method has completed, then you can pass the callback handler method, which accepts IAsyncResult object, while calling BeginInvoke method. This allows the instigating thread to “forget” about the asynchronous delegate, but it requires a bit of extra work at the callback end as you can see in the given example.

The final argument to BeginInvoke is a user state object that populates the AsyncState property of IAsyncResult. It can contain anything you like; in this case, we’re using it to pass the method delegate to the completion callback, so we can call EndInvoke on it.

Thread Pooling – BackgroundWorker >>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Adarsh Chaurasia - Enjoying Full Stack Development
Software Developer (Senior)
India India
 Innovative & tech-savvy software development professional with 6+ years of progressive experience specializing in object-oriented approach to enterprise commercial solution delivery utilizing latest technologies.
 Extensive background in Full Life-Cycle of Software Development and Automation process including requirements gathering, design, coding, unit testing, automation, debugging and maintenance.
 Comprehensive knowledge of Relational Database technology, queries and procedures.
 Excellent understanding of OOPS Concepts, Design Patterns & Best Coding Practices.
 Strong architectural knowledge of designing n-tier and n-layer solutions using Application blocks, Enterprise library, SOA, Software factories.
 Working experience of IIS administration and website deployment and configuration.

Strengths & Area of expertise include:

 Full Stack Enterprise Web Development
 Multi-Threaded Programming
 Object Oriented Development
 REST APIs Development & Integration
 Distributed/Client Server System
 TDD & Behavior Driven Development (BDD)
 Database Design & Development
 Exceptional Analytical & Quick Learning Skill
 Team & Client Communication
 Proactive & Organization Development Attitude

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160826.1 | Last Updated 18 Feb 2014
Article Copyright 2014 by Adarsh Chaurasia - Enjoying Full Stack Development
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid