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.
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 Begin
Whatever
method. (BeginExecuteReader
, BeginGetResponse
, and many others). The Begin
Whatever
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 Begin
Whatever
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 End
Whatever
method that corresponds to the Begin
Whatever
method you called in the first place. You have to give it the IAsyncResult from Begin
Whatever
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, End
Whatever
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 Begin
Whatever
and End
Whatever
methods that return and take it, respectively. For more information on implementing IAsyncResult, see here.