Asynchronous method calls in c# [part 1]

Planning to write something interesting, yet very useful, I thought of writing about asynchronous calls. Before that, first we need to know the two categories of method calls.

Note:This post will be partioned in to two. This one will be just an introduction to the asynchronous calls.

There are two methods of method calls (crappy sentence nah ??)

Synchronous method call

This is the traditional method call, calling the method directly from another method. What happens in here is the control, as soon as it sees a method call, will jump to the target and start to execute that one. Only after finishing that one will come bak to the originator (or the caller). For example,

ln: 100 private void Foo()
ln: 101 {
ln: 102   //some crappy logics
ln: 103   Bar();
ln: 104 }
ln: 105  private void Bar()
ln: 106 {
ln: 107   //again some logics are done in here
ln: 108 }

In the above snippet, when the control sees the call Bar(); (ln: 103), will directly jump to the Bar() function (ln: 105) and start to execute the method. After the completion of this will return to the caller (ln: 104).

This is the normal method call. Suppose if the Bar() method (ln: 105) has too many logics in it and if it takes a long time to execute, then the control will come to the caller (ln. 104) only after successfully finishing all those logics. This may sound obvious, but not soo good when it comes to the GUI programming.

Considering that the Foo() method (ln: 100) is called on a button clicked event, then the UI will remain frozen until the control finishes executing Foo() method (there by executing the Bar() function). This freezing of the UI can be (rather should be) avoided by using asynchronous calls.

Asynchronous calls

Asynchronous calls are like event. They are of “fire and forget” type you can say. Considering the above quoted example, the Foo() method (ln: 100) now will make an asynchronous call to the Bar() method (ln: 105). Programatical explanation will be given in the next post. The charm for such a method call is that, as soon as the Foo() method calls Bar() method, asynchronously, the control still remains in Foo() and the Bar() method will be running in another thread. So in the GUI applications there won’t be any freezing of UI if such calls are made. Yeah, its a great feature.

Also I should talk about call backs while explaining asynchronous calls. Suppose that you wanna update some information in the UI when a button is clicked and for which, it may take a long time, now what you do is, make an asynchronous call. But the question is “How will you know when the asynchronous call has been completed ??” The processing of making the application to notify you on finishing an asynchronous call is called callback. All these will be explained more clearly in the next post.

Tags: , , , ,

2 comments

  1. I got a clear cut idea of async calls from this post.
    Looking forward for the second part.

Leave a comment