Click here to Skip to main content
15,891,903 members
Articles / Delegates
Technical Blog

Calling a method in C# asynchronously using delegates

Rate me:
Please Sign up or sign in to vote.
3.75/5 (19 votes)
23 Jul 2012CPOL1 min read 122.6K   17   4
Another useful feature of delegates is the ability to execute a method asynchronously. That is, through a delegate, you can begin invocation of a method and then return immediately while the delegate executes its method in a separate thread.

Another useful feature of delegates is the ability to execute a method asynchronously. That is, through a delegate, you can begin invocation of a method and then return immediately while the delegate executes its method in a separate thread. Your page execution does not need to wait for that method to complete.

The following example demonstrates the use of delegates for asynchronous method invocation. To see this in action we need a method that simulates a lengthy operation, such as writing data to db logs, record page hits that can be asynchronous, and do not affect the end client response.

C#
public delegate void LongTimeTask_Delegate(string s);
 
protected void Page_Load(object sender, System.EventArgs e)
 {
 if (!Page.IsPostBack)
 {
 
// databind of all the controls
 
LongTimeTask_Delegate d = null;
 d = new LongTimeTask_Delegate(LongTimeTask);
 
IAsyncResult R = null;
 R = d.BeginInvoke("TestString", null, null); //invoking the method
 }
 }

In the above load event of the page after binding all the UI controls we need to perform a lengthy operation to record something in DB or any IO operation file. We are initializing the deligate with the LongTimeTask method, and delegate.BeginInvoke will call the method below asynchronously. Later we will see how to know if the method invokation completed successfully or not.

C#
public void LongTimeTask(string s)
 {
 // Write your time consuming task here
 }

Now, if we would want to perform an another operation after the above method is completed, That is called callback approach, add the async call back event in beginInvoke:

C#
//using callback approach
 R = d.BeginInvoke("TestString", new AsyncCallback(TaskCompleted), null);
 
public void TaskCompleted(IAsyncResult R)
 {
 // Write here code to handle the completion of
 // your asynchronous method
 }

The above method will execute on completion of LongTimeTask method.

We can also wait untill the LongTimeTask is execution is completed or not, but then that will not serve the purpose of calling it asynchronously, but still you would need it somewhere:

C#
//this will block until the asynchronous operation is complete

d.EndInvoke(R);

Try it out at your end, I have just given you the skeleton that I have tried, It works fine, but just be careful, as this works on a separate thread, which might sometimes consumes a lot of memory / CPU usage.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
Questionhelp full Pin
Amrik Singh4-Mar-15 9:52
Amrik Singh4-Mar-15 9:52 
QuestionSystem.Threading.Tasks Pin
Ivan Ičin30-Jul-12 11:16
Ivan Ičin30-Jul-12 11:16 
AnswerRe: System.Threading.Tasks Pin
SteveGuiri20-Jan-14 12:33
SteveGuiri20-Jan-14 12:33 
GeneralRe: System.Threading.Tasks Pin
Ivan Ičin20-Jan-14 12:57
Ivan Ičin20-Jan-14 12:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.