What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 7008 |  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: 8506 | 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 article demonstrates how to copy DLL from Global Assembly Cache.

This is next write-up in the multi-part series for SQL Server Integration with CLR aka SQL CLR and discusses the creation of SQL server User Defined Function in SQL CLR.

In this application it is discussed how you can use Windows Narrator to create talking application.

N.B, This article is for newbies. I remember my early days of my programming,The most battle i used to have was how to display my data on my form, yes i used GridViews, but find limitations when dealing with data.

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 aggregate in SQL CLR.

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/22/2013 10:38:48 AM