Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » C# Language » Asynchronous Nature of Delegates

Asynchronous Nature of Delegates

In this article you will see the other face of the delegate type in C#, it will show you how you can invoke a method asynchronously using delegates.

Page Views : 32036
Downloads : 504
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
AsyncronousNaturOfDelegates.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 



Introduction

Building a multithreaded application can be done in several ways includes:

  1. Asynchronous delegates calls.
  2. The BackgroundWorker component.
  3. The Thread class.

In this article we will cover the asynchronous delegates calls, if you want to know about other two types see my articles (Using the BackgroundWorker component, Building a multithreaded application using Thread calss).

This article assumes that you have a good understanding of the delegate type, if you don't, see my article Delegates in C#.
Asynchronous delegates calls:
as you may know, we use the delegate to point to method in the application, which can be invoked at later time.

Example 1:

namespace DelegateSynchronousCalls

{

    public delegate int MyDelegate(int x);

    public class MyClass

    {

        //A method to be invoke by the delegate

        public int MyMethod(int x)

        {

            return x * x;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            MyClass myClass1 = new MyClass();

            MyDelegate del = new MyDelegate(myClass1.MyMethod);

 

            //invoke the method synchronously

            int result = del(5);

            //this text will not show till the first operation finish

            Console.WriteLine("Proccessing operation...");

            Console.WriteLine("Result is: {0}", result);

            Console.ReadLine();

        }

    }
}

As you can see we used our delegate to invoke the method in the main thread of our application, but what if we have a long runing proccess that will be executed when we invoke the method, for example:

public
int MyMethod(int x)

{

    //simulate a long running proccess

    Thread.Sleep(10000);

    return x*x;   

}

We have now an operation that will take about 10 second to complete so our application will be not responsive and we can't execute any other operations till the first one finish.

So, what we can do to overcome this problem?

The answer is to use the delegate to invoke the method asynchronosly, but how we can do this?. The next example will show you how to use our delegate to make asynchronous call of the method.

Example 2:

namespace
DelegatesAsynchronousCalls

{

    class Program

    {

        public delegate int MyDelegate(int x);

        public class MyClass

        {

            //A method to be invoke by the delegate

            public int MyMethod(int x)

            {

                //simulate a long running proccess

                Thread.Sleep(10000);

                return x * x;

            }

        }

        static void Main(string[] args)

        {

            MyClass myClass1 = new MyClass();

            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our method in another thread

            IAsyncResult async = del.BeginInvoke(5, null, null);

            //do something while MyMethod is executing.

            Console.WriteLine("Proccessing operation...");

            //recieve the results.

            int result = del.EndInvoke(async);

            Console.WriteLine("Result is: {0}", result);

            Console.ReadLine();

        }

    }

}

As you can see, we defined the delegate as usual but we don't start invoking our method directly, we used our delegate to call BeginInvoke() method that returns an IAsyncResult object, then we submit this object to the EndInvoke() method then EndInvoke() provide the return value.(complex right !!?)

You may wonder now from where all this methods come from?

The answer is simple, when you define a delegate, a custom delegate class is generated and added to your assembly. this class include many method like Invoke(), BeginInvoke() and EndInvoke().

When you use your delegate to call a method you actualy call the Invoke() method. Invoke() method executes your method synchronously (on the main thread) as in example 1.

When you want to make an asynchronous call to your underlying method first you call BeginInvoke(). When you call BeginInvoke() your method is queued to start on another thread. 

BeginInvoke() doesn't return the return value of the underlying method. Instead it returns an IAsyncResult object that you can use to determine when the asynchronous operation is complete.

To take your results, you submit the IAsyncResult object to the EndInvoke() method of the delegate. EndInvoke() waits for the operation to complete if it hasn't already finished and then provide the return value.

You may ask, what is the other two parameters in the BeginInvoke() method?

When calling BeginInvoke() you supply all the parameters of the original method, plus two parameters, the first can be used in callback and the othe is a state object. if you don't need these options just pass a null reference.

In the next section you will see how to use them.

Using AsyncCallback delegate:

To alow the calling thread to know if the asynchronous operation has completed its work, you have two ways to do this, first you can make use of the IsCompleted property of the IAsyncResult interface.

By using this property, the calling thread is able to determine is the asynchronous operation has completed before calling EndInvoke(). If the method has not completed, IsCompleted returns false. If IsCompleted return true, the calling thread can obtain the results

Example 3:

namespace DelegatesAsyncCallsIsCompleted

{

    public delegate int MyDelegate(int x);

    public class MyClass

    {

        //A method to be invoke by the delegate

        public int MyMethod(int x)

        {

            //simulate a long running proccess

            Thread.Sleep(3000);

            return x * x;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            MyClass myClass1 = new MyClass();

            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread

            IAsyncResult async = del.BeginInvoke(5, null, null);

 

            //loop until the method is complete

            while (!async.IsCompleted)

            {

                Console.WriteLine("Not Completed");

            }

            int result = del.EndInvoke(async);

            Console.WriteLine("Result is: {0}", result);

            Console.ReadLine();

        }

    }

}

It would be more efficient when we have a delegate that inform the calling thread when the operation is finished.

To do this, you need to supply an instance of the AsyncCallback delegate as a parameter to BeginInvok(). This delegate will call a specified method automaticaly when the asynchronous call has completed.

The method that AsyncCallback will invoke must taking IAsyncResult as a sole parameter and return nothing.

public
static void MyCallBack(IAsyncResult async)

{

}

The IAsyncResult is the same object that you recieve when you call BeginInvoke() method.

Example 4:

namespace
AsyncCallbackDelegate

{

    public delegate int MyDelegate(int x);

    public class MyClass

    {

        //A method to be invoke by the delegate

        public int MyMethod(int x)

        {

            //simulate a long running proccess

            Thread.Sleep(10000);

            return x * x;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            MyClass myClass1 = new MyClass();

            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread

            IAsyncResult async = del.BeginInvoke(5, new AsyncCallback(MyCallBack), null);

            Console.WriteLine("Proccessing the Operation....");

            Console.ReadLine();

        }

        static void MyCallBack(IAsyncResult async)

        {

            Console.WriteLine("Operation Complete);

        }

    }

}

Remember, the MyCallback() method will be invoked by the AsyncCallback delegate when the MyMethod() has completed.
As you can see, we didn't invoke the EndInvoke() method that because the MyCallback() method doesn't have access to the MyDelegate object, so we can make use of the incoming IAsyncResult parameter and cast it into type AsyncResult and use the static AsyncDelegate property which returns a reference to the original asynchronous delegate that was created else where.

We can rewrite the MyCallback() method as follow:

static
void MyCallBack(IAsyncResult async)

{

    AsyncResult ar = (AsyncResult)async;

    MyDelegate del = (MyDelegate)ar.AsyncDelegate;

    int x = del.EndInvoke(async);

    Consol.WriteLine("Operation Complete, Result is: {0}", x);

}


The final parameter of the BeginInvoke() method can be used to pass additional state information to the callback method from the primary thread. Because this parameter is a System.Object, you can pass in any type of information .
Exampe 5:

namespace
AsyncCallbackDelegate

{

    public delegate int MyDelegate(int x);

    public class MyClass

    {

        //A method to be invoke by the delegate

        public int MyMethod(int x)

        {

            //simulate a long running proccess

            Thread.Sleep(10000);

            return x * x;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            MyClass myClass1 = new MyClass();

            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread

            IAsyncResult async = del.BeginInvoke(5, new AsyncCallback(MyCallBack), "A message from the main thread");

            Console.WriteLine("Proccessing the Operation....");

            Console.ReadLine();

        }

        static void MyCallBack(IAsyncResult async)

        {

            AsyncResult ar = (AsyncResult)async;

            MyDelegate del = (MyDelegate)ar.AsyncDelegate;

            int x = del.EndInvoke(async);

 

            //make use of the state object.

            string msg = (string)async.AsyncState;

            Console.WriteLine("{0}, Result is: {1}", msg, x);

        }

    }

}

I hope this article helped you a little bit in understanding the asynchronous nature of delegates. See you.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Amr Monjid
Amr Monjid is a computer programmer from Egypt. He has experience with C#, .Net framework, ASP.NET, Windows Applications, ADO.NET, Xml, Web Services, Custom Controls, and e-commerce web sites. and he is a MCTS: .NET framework 2.0, Windows Application, Distributed Aplication.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Great job - thanks by Anthony On January 18, 2009
Hi Amr, Thank you very much for this tutorial, I found it very helpful. Regards, Anthony (Ireland).
Reply | Email | Modify 
Good article by Niladri On April 13, 2009
Thanks man...Many doubts of mine are cleared now. I am felling comfortable slowly in using delegates. Thanks buddy. Cheers!
Reply | Email | Modify 
very good article by danny On September 7, 2009
This article helped me alot with understanding how to use async webrequests, Thanks!

-----------------------
Danny, Los Angeles Locksmith
Reply | Email | Modify 
how to use these Asynchronous delegates in events by Koteswararao On September 3, 2010
suppose i have a 3 fileWatcherConrols i bind the 3 controls events to corresponding event handlers suppose for all rename event one rename event handler how can we use this in this situation
Reply | Email | Modify 
Another Great Article. by Danny On October 19, 2010
Wish there were more like it. You let me see the whole wood, not just the trees!
Reply | Email | Modify 
Thank You Vey much by Ravi On October 19, 2011
Good Explanation. The Article helped me a Lot
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.