18.10 Performing Asynchronous Remoting Calls

 <  Day Day Up  >  

You want to invoke the remoting calls asynchronously. Calling methods across the network can take a while. So that the client doesn't have to wait until a method finishes, the method can be called asynchronously.


Technique

To invoke a method of a remoting object asynchronously, you can create a delegate with the same signature and return type as the method of the remote object:

 
 public delegate string GreetingDelegate(string s); 

Creating a delegate instance, you can pass the method of the remote object to the constructor of the delegate. The sample code passes the method Greeting . Then, you can start the method Greeting by invoking the method BeginInvoke using the delegate instance. BeginInvoke accepts the same parameters as the input parameters of the method Greeting and two parameters more. The first additional parameter is of type AsyncCallback , which lets you specify a method that should be called when the Greeting method is finished. The second additional parameter lets you pass any object that can be accessed again when the method completes:

 
 GreetingDelegate del1 = new GreetingDelegate(obj.Greeting); // start the method call IAsyncResult ar = del1.BeginInvoke("Simon", null, null); // do something else 

After the method starts, you can check whether the asynchronous method is already completed with the IAsyncResult object that is returned from BeginInvoke . Calling EndInvoke waits until the asynchronous method is completed:

 
 string greeting = del1.EndInvoke(ar); 

Comments

Using delegates, you can invoke any method in an asynchronous way. There's no difference whether you are calling .NET Remoting objects or not.

Delegates allow different ways to get the return values from the asynchronous method: you can pass an AsyncCallback delegate that specifies the method which should be called when the asynchronous method completes, you can check with the IAsyncResult object whether the method is finished, and you can wait until the method is completed with EndInvoke .

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net