This documentation is archived and is not being maintained.

How to: Call the Methods of a Remote Object Asynchronously

This topic is specific to a legacy technology that is retained for backward compatibility with existing applications and is not recommended for new development. Distributed applications should now be developed using the  Windows Communication Foundation (WCF).

The process for asynchronous programming is as straightforward as that for a single application domain.

To call a method of a remote object asynchronously

  1. Create an instance of an object that can receive a remote call to a method.

    ServiceClass obj = new ServiceClass();
  2. Wrap the callback method with an AsyncCallback object.

    AsyncCallback RemoteCallback = new AsyncCallback(this.OurRemoteAsyncCallback);
  3. Wrap the remote method which you want to call asynchronously with an appropriate delegate.

    public delegate string RemoteAsyncDelegate();
    RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.RemoteMethod);
  4. Call BeginInvoke method on the second delegate, passing any arguments, the AsyncDelegate, and some object to hold state (or a null reference — Nothing in Visual Basic).

    IAsyncResult RemAr = RemoteDel.BeginInvoke(RemoteCallback, null);
  5. Wait for the remote object to call your callback method.

    While this is the general approach, you can vary it to some degree. If you want at any point to wait for a particular call to return, you merely take the IAsyncResult interface that was returned from the BeginInvoke call, retrieve the WaitHandle instance for that object, and call the WaitOne method as shown in the following code example.


    Alternatively, you can wait either in a loop that checks whether the call has completed as shown in the following sample code.

    int count = 0;
    while (!RemAr.IsCompleted)
        Console.Write("\rNot completed: " + (++count).ToString());

    Finally, you can have your main thread create a ManualResetEvent and wait on the callback function, which then signals the ManualResetEvent as the last line prior to returning. For an example of this type of wait, see the source code comments in Remoting Example: Asynchronous Remoting.

See Also