Congratulations to all the winners of April 2013, they have won INR 3400 cash and INR 20147 worth prizes !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 11357 |  Welcome, Guest!   Register  Login
Home > Articles > .NET Framework > Asynchronous Method Invocation

Asynchronous Method Invocation

2 vote(s)
Rating: 3 out of 5
Article posted by Abhi2434 on 3/4/2010 | Views: 8498 | Category: .NET Framework | Level: Beginner red flag


Here I am showing how you can invoke a method asynchronously using delegates and AsyncCallback

Download


 Download source code for Asynchronous Method Invocation


Introduction

In our daily life, we often come across a situation where we need to invoke a method in a new thread. We generally create a new thread directly and use it. Well, it is not actually recommended to create a Thread as and when required. So we use ThreadPool to have a better use of available threads and also configure it our self.
Thus we require a considerable amount of code to just call a method in another thread. Delegates comes with methods like BeginInvoke which is used to call a method Asynchronously and with proper usage of ThreadPool. We will be discussing that to you with the most simple example.

Synchronous Call

Delegates are generally used to hold method definition and to call it whenever it is required. We can use delobj.Invoke(params) or delobj(params) to invoke a delegate. In the sample application we create a method which simply adds up two numbers. To do this we have created :

private delegate int AddOperationDelegate(int x, int y);

private void button3_Click(object sender, EventArgs e)

{

AddOperationDelegate del = new AddOperationDelegate(add);

lblResult.Text = "Synchronous work Started !";

lblResult.Update(); //This is necessary to repaint the window before calling Thread.Sleep

int res = del.Invoke(10, 20); // or del(10, 20);

MessageBox.Show(string.Format("Result generated : {0}", res));

}

In the method Add we just wrote :

private int add(int x, int y)

{

Thread.Sleep(4000); //Makes the thread to sleep, to make you understand it creates a new thread.

return x + y;

}

Thus you can see the delegate AddOperationDelegate(int x, int y) is called synchronously using del.Invoke(). The method add is called during this operation and the output will be shown using the message box. If you try the sample application you should notice, that after you click on the Synchronous button, the window gets hanged and you cannot do any operation.
This is actually happening because the current thread is blocked using Thread.Sleep which is invoked inside the add method to halt the application for 4 seconds. This might be a long running process. 

Asynchronous Call


To eliminate this issue we might take the help of BeginInvoke and EndInvoke, which actually creates a new thread and invoke the method from there. To do this let us look how the Asynchronous button looks like :

private void btnAsynchronous_Click(object sender, EventArgs e)

{

AddOperationDelegate del = new AddOperationDelegate(add);

IAsyncResult res = del.BeginInvoke(10, 20, new AsyncCallback(InvokeMessage), null);

lblResult.Text = "Asynchronous work Started !";

}

private void InvokeMessage(IAsyncResult ar)

{

AddOperationDelegate aod = (ar as AsyncResult).AsyncDelegate as AddOperationDelegate;

int result = aod.EndInvoke(ar);

MessageBox.Show(string.Format("Result generated : {0}", result));

}

In the above code you can see I have called BeginInvoke instead of normal Invoke. BeginInvoke actually creates a new thread from the ThreadPool and calls the method. If it is a multicast delegate, it will call that many Threads and call them. The AsyncCallBack is called when the thread execution is complete and the result can be obtained.

We have passed InvokeMessage to get the result. We simply cast the object into AsyncDelegate into our own delegate object and use EndInvoke to get the result back.


Conclusion
Thus we can see, it is very easy to make use of BeginInvoke and EndInvoke with delegates to create a new thread from ThreadPool, and we dont require to create the thread ourself.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Abhishek Sur

Experience:3 year(s)
Home page:http://www.abhisheksur.com
Member since:Wednesday, December 02, 2009
Level:Silver
Status: [Member] [Microsoft_MVP] [MVP]
Biography:Working for last 2 and 1/2 years in .NET environment with profound knowledge on basics of most of the topics on it.
>> Write Response - Respond to this post and get points
Related Posts

This is next write-up in the multipart series for SQL Server Integration with CLR aka SQL CLR and discusses the creation of SQL server trigger through SQL CLR.

This article delves into the feature (of SQL server) of returning the multiple resultsets and handling such multiple resultsets implemented through inline SQL and as well as through stored procedure in C# with dataset.

In this article, let us see how to bind a combobox with different columns from different datatables. eg. I have a datatable “Server” with columns server and database. Another datatable “server1” with columns servername and database name. Now I want to display all the values in the server and server name columns into a single combobox.

In this article we will understand core reasons of why we should use LINQ. Three tier / N-Tier is now a standard in almost all projects. New architectures which are coming up like MVC, MVP have the fundamental base and thinking of 3-tier methodology. So we have termed the 3-tiers as SALT, in other words we can not stay with out it. LINQ (Pepper) on other hand is a new technology which helps us create execute queries against disparate data sources like ADO.NET, Custom objects, XML etc. So it’s not a needed thing (Pepper) but it does helps to remove lot of issues related with traditional 3-tier. So let’s make a nice Three-tier LINQ dish using SALT and PEPPER. So we will first understand Three-tier, issues with it and then see how LINQ helps us to improve the same.

This Article Demonstrates the Process of Serialization and De-Serialization in VB.NET

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/20/2013 1:39:57 AM