Go to DotNetFunda.com
 Online : 592 |  Welcome, Guest!   Login
 
Home > Articles > .NET Framework > Asynchronous Method Invocation

Submit Article | Articles Home | Search Articles |

Asynchronous Method Invocation

1 vote(s)
Rating: 1 out of 5
red flag  Posted on: 3/4/2010 4:36:07 PM by Abhi2434 | Views: 2496 | Category: .NET Framework | Level: Beginner


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.

Found interesting? Add this to:

| More



Please Sign In to vote for this post.

 
Latest post(s) from Abhi2434

Latest Articles

About Abhishek Sur

Experience:3 year(s)
Home page:http://www.abhisheksur.com
Member since:Wednesday, December 02, 2009
Level:Silver
Status: [Member]
Biography:Working for last 2 and 1/2 years in .NET environment with profound knowledge on basics of most of the topics on it.

Submit Article

About Us | The Team | Advertise | Contact Us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found 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. | 9/3/2010 3:40:54 AM