Asynchronous Calls in .NET

Synchronous means occurring at the same time, at the same rate, or with a regular or predictable time relationship or sequence. Asynchronous means not synchronized by a shared signal such as a clock or semaphore, proceeding independently. Refer to a basic computer science text if you are not familiar with these concepts. You must consider the trade-offs when deciding between the two types. Synchronous calls run faster but must activate and run immediately. If you have relatively few calls, that type may be preferable. Asynchronous calls run slower but activate and run whenever the response is received. If you have many calls, that type may be preferable. Multithreaded applications, in particular, should be coded in an asynchronous style because you cannot make estimations about the receive time of the relevant stream or data for any of the threads. The synchronous call strategy might not always be desirable because the remote object might have to perform a number of time-consuming tasks, and it is not advisable to block the client while a call is in progress. In our next example, we will see a variation of the SoapClientProtocol implementation. 

In Listing 23.21 the callback declares an object of the type IAsyncResult as the parameter of the callback function. Once the call completes, the framework ensures that the result of the call is placed inside the result object, and the callback is then invoked back to the client, forwarding the result object to it. To retrieve the result of the call, we simply extract the delegate from the AsyncResult and call EndInvoke. We create a delegate for the callback method and one for the remote method; we call the method by calling BeginInvoke on the delegate, and simply wait for the result to return from the server. The compiler automatically generates the class MyDelegate when it encounters the declaration and adds a BeginInvoke and EndInvoke method to the delegate that maps to native calls somewhere in the CLR. 

After making an asynchronous call, the next thing to do is to create the callback function that receives the result from the call. We could code the asynchronous interface client for our previous SOAP remote object server as in Listing 23.21. 

Listing 23.21: Asynchronous Call SOAP with Null Parameter 

            
AsyncCallback mycallback = new syncCallback(Client.MyCallBack);

            MyDelegate mydelegate =
new MyDelegate(obj.DateTimeMethod);

            
IAsyncResult ar = mydelegate.BeginInvoke("Clown Bozo",
            mycallback, null);

                    
public static void MyCallBack(IAsyncResult ar)
        {
            MyDelegate d = (MyDelegate)ar.AsyncObject;
            Console.WriteLine(d.EndInvoke(ar));
        }