다음을 통해 공유


방법: 원격 개체의 메서드를 비동기로 호출

비동기 프로그래밍 과정은 단일 응용 프로그램 도메인의 경우만큼 간단합니다.

원격 개체의 메서드를 비동기로 호출하려면

  1. 메서드에 대한 원격 호출을 받을 수 있는 개체의 인스턴스를 만듭니다.

  2. 해당 인스턴스 메서드를 AsyncDelegate 개체로 래핑합니다.

    Dim RemoteCallback As New AsyncCallback(AddressOf Me.OurCallBack)
    
    AsyncCallback RemoteCallback = new AsyncCallback(this.OurCallBack);
    
  3. 원격 메서드를 다른 대리자로 래핑합니다.

    Dim RemoteDel As New RemoteAsyncDelegate(AddressOf obj.RemoteMethod)
    
    RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.RemoteMethod);
    
  4. 두 번째 대리자에 대해 BeginInvoke 메서드를 호출하고 인수 및 AsyncDelegate, 그리고 상태를 저장할 특정 개체(또는 null 참조, Visual Basic에서는 Nothing)를 전달합니다.

    Dim RemAr As IAsyncResult = RemoteDel.BeginInvoke(RemoteCallback, _
                                Nothing)
    
    IAsyncResult RemAr = RemoteDel.BeginInvoke(RemoteCallback, null);
    
  5. 서버 개체가 콜백 메서드를 호출하기를 기다립니다.

    이 방법이 일반적인 방법이지만 이와는 약간 다른 방법을 사용할 수도 있습니다. 임의의 시점에서 특정 호출이 반환되기를 기다리려는 경우에는 다음 코드 예에서처럼 BeginInvoke 호출에서 반환된 IAsyncResult 인터페이스를 사용하고 해당 개체에 대해 WaitHandle 인스턴스를 검색한 다음 WaitOne 메서드를 호출하기만 하면 됩니다.

    RemAr.AsyncWaitHandle.WaitOne()
    
    RemAr.AsyncWaitHandle.WaitOne();
    

    그렇지 않으면 다음 샘플 코드에서와 같이 호출이 완료되었는지 여부를 확인하는 루프에서 또는 ManualResetEvent 클래스 등의 System.Threading 기본 형식을 사용하여 기다린 다음 호출을 직접 완료할 수도 있습니다.

    If RemAr.IsCompleted Then
      Dim del As RemoteAsyncDelegate = CType(CType(RemAr, AsyncResult).AsyncDelegate, RemoteAsyncDelegate)
      Console.WriteLine(("SUCCESS: Result of the remote AsyncCallBack:" _
        + del.EndInvoke(RemAr)))
    ' Allow the callback thread to interrupt the primary thread to execute the callback.
    Thread.Sleep(1)
    End If ' Do something.
    
    if (RemAr.IsCompleted){
      RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult) RemAr).AsyncDelegate;
      Console.WriteLine("SUCCESS: Result of the remote AsyncCallBack: "  
        + del.EndInvoke(RemAr) );
    // Allow the callback thread to interrupt the primary thread to execute the callback.
    Thread.Sleep(1);
    }
    
  6. 마지막으로 주 스레드에서 ManualResetEvent를 만들고 콜백 함수를 기다리도록 할 수 있습니다. 콜백 함수는 반환하기 전에 ManualResetEvent를 마지막 줄에 포함시켜 알림을 전달합니다. 이러한 유형의 대기에 대한 예는 원격 서비스 예: 비동기 원격 서비스에 있는 소스 코드 주석을 참조하십시오.

참고 항목

개념

원격 서비스 예: 비동기 원격 서비스
원격 응용 프로그램의 구성

기타 리소스

.NET Framework Remoting 개요