Synchronous and asynchronous callbacks

user160677 picture user160677 · Aug 30, 2009 · Viewed 8.3k times · Source

I get confused with some terms while reading MSDN documents and code samples.

What are callbacks in C#? In particular, what are synchronous and asynchronous callbacks ?

Please explain these from a layman's point of view.

Also, please explain the IAsyncCallback IAsyncResult interface. How can we implement it? (with very simple example)

Thanks in advance.

Answer

SLaks picture SLaks · Aug 30, 2009

The IAsyncCallback interface does not exist, so you cannot implement it.

I suspect that you actually want to know about the IAsyncResult interface.

I recommend that you read this page on MSDN.


The IAsyncResult interface represents an operation (such as a web request or a database call) that is running in the background, while your code continues to execute. It can tell you whether the operation finished (the IsCompleted property). It also gives you a WaitHandle object (the AsyncWaitHandle property) which can be used to wait until the operation finishes. (By calling result.AsyncWaitHandle.WaitOne())

You get an IAsyncResult by calling a BeginWhatever method. (BeginExecuteReader, BeginGetResponse, and many others). The BeginWhatever method will take any parameters needed for the operation (For example, BeginExecuteReader can take a CommandBehavior parameter), and can take an AsyncCallback delegate (not interface) and a state parameter. In returns an IAsyncResult object.

The AsyncCallback delegate is a method that you supply, which will be called when the operation finishes. It will usually be called on a different thread, so be careful in it. Your AsyncCallback method will be given the same IAsyncResult that the BeginWhatever method gave you earlier. The state parameter is put into the IAsyncResult and ignored by the system; you can use it in your AsyncCallback method to keep track of what the operation was for. (The state can be whatever you want it to be, including null)

Inside your AsyncCallback (or anywhere else), you can call the EndWhatever method that corresponds to the BeginWhatever method you called in the first place. You have to give it the IAsyncResult from BeginWhatever or from the AsyncCallback. When you call it, it will wait for the operation to finish (if it isn't already finished), and then give you back the operation's result. (Assuming the operation returns something; for example, WebRequest.EndGetResponse will return a WebResponse). If any error occurred during the operation, EndWhatever will throw an exception.


You would implement IAsyncResult if you want to create your own operation that can run in the background. You would also create BeginWhatever and EndWhatever methods that return and take it, respectively. For more information on implementing IAsyncResult, see here.