Blue Theme Orange Theme Green Theme Red Theme
 
ASP.NET Web Hosting – Click Here
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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.

Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads : 217
Total page views :  11592
Rating :
 4.83/5
This article has been rated :  12 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
AsyncronousNaturOfDelegates.zip
 
ArticleAd
Become a Sponsor



Introduction

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

  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 assume 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.


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.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
AsyncronousNaturOfDelegates.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Great job - thanksAnthony1/18/2009
Hi Amr, Thank you very much for this tutorial, I found it very helpful. Regards, Anthony (Ireland).
Reply | Email | Delete | Modify | 
Good articleNiladri4/13/2009
Thanks man...Many doubts of mine are cleared now. I am felling comfortable slowly in using delegates. Thanks buddy. Cheers!
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved