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.

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

    Dim RemoteCallback As New AsyncCallback(AddressOf Me.OurRemoteAsyncCallback)
  3. Wrap the remote method which you want to call asynchronously with an appropriate delegate.

    Delegate Function RemoteAsyncDelegate() As String
    Dim RemoteDel As New RemoteAsyncDelegate(AddressOf 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).

    Dim RemAr As IAsyncResult = RemoteDel.BeginInvoke(RemoteCallback, Nothing)
  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.

    Dim count As Integer = 0
    While Not RemAr.IsCompleted
      Console.Write("Not completed -- " & count & vbCr)
      count += 1
      Thread.Sleep(New TimeSpan(TimeSpan.TicksPerMillisecond))
    End While

    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

Copyright © 2007 by Microsoft Corporation. All rights reserved.

Community Additions