다음을 통해 공유


AsyncResult 클래스

비동기 대리자가 수행하는 비동기 작업의 결과를 캡슐화합니다.

네임스페이스: System.Runtime.Remoting.Messaging
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<ComVisibleAttribute(True)> _
Public Class AsyncResult
    Implements IAsyncResult, IMessageSink
‘사용 방법
Dim instance As AsyncResult
[ComVisibleAttribute(true)] 
public class AsyncResult : IAsyncResult, IMessageSink
[ComVisibleAttribute(true)] 
public ref class AsyncResult : IAsyncResult, IMessageSink
/** @attribute ComVisibleAttribute(true) */ 
public class AsyncResult implements IAsyncResult, IMessageSink
ComVisibleAttribute(true) 
public class AsyncResult implements IAsyncResult, IMessageSink

설명

AsyncResult 클래스는 비동기 대리자와 함께 사용됩니다. 대리자의 BeginInvoke 메서드에서 반환되는 IAsyncResultAsyncResult로 캐스팅될 수 있습니다. AsyncResult는 비동기 호출이 호출된 대리자 개체를 포함하는 AsyncDelegate 속성을 갖습니다.

BeginInvoke와 비동기 대리자에 대한 자세한 내용은 대리자를 사용한 비동기 프로그래밍을 참조하십시오.

예제

다음 코드 예제에서는 AsyncResult 클래스를 사용하여 비동기 대리자의 비동기 작업 결과를 검색하는 방법을 보여 줍니다.

Imports System
Imports System.Threading
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Contexts
Imports System.Runtime.Remoting.Messaging


' Context-bound type with the Synchronization context attribute.
<Synchronization()> Public Class SampleSyncronized
   Inherits ContextBoundObject
   
   ' A method that does some work, and returns the square of the given number.
   Public Function Square(i As Integer) As Integer
      
      Console.Write("The hash of the thread executing ")
      Console.WriteLine("SampleSyncronized.Square is: {0}", Thread.CurrentThread.GetHashCode())
      Return i * i
   End Function 'Square

End Class 'SampleSyncronized

' The async delegate used to call a method with this signature asynchronously.
Delegate Function SampSyncSqrDelegate(i As Integer) As Integer


Public Class AsyncResultSample
   
   ' Asynchronous Callback method.
   Public Shared Sub MyCallback(ar As IAsyncResult)
      ' Obtains the last parameter of the delegate call.
      Dim value As Integer = Convert.ToInt32(ar.AsyncState)
      
      ' Obtains return value from the delegate call using EndInvoke.
      Dim aResult As AsyncResult = CType(ar, AsyncResult)
      Dim temp As SampSyncSqrDelegate = CType(aResult.AsyncDelegate, SampSyncSqrDelegate)
      Dim result As Integer = temp.EndInvoke(ar)
      
      Console.Write("Simple.SomeMethod (AsyncCallback): Result of ")
      Console.WriteLine("{0} in SampleSynchronized.Square is {1} ", value, result)
   End Sub 'MyCallback  

   Public Shared Sub Main()
      
      Dim result As Integer
      Dim param As Integer
      
      ' Creates an instance of a context-bound type SampleSynchronized.
      Dim sampSyncObj As New SampleSyncronized()
      
      ' Checks whether the object is a proxy, since it is context-bound.
      If RemotingServices.IsTransparentProxy(sampSyncObj) Then
         Console.WriteLine("sampSyncObj is a proxy.")
      Else
         Console.WriteLine("sampSyncObj is NOT a proxy.")
      End If 

      param = 10
      
      Console.WriteLine("")
      Console.WriteLine("Making a synchronous call on the context-bound object:")
      
      result = sampSyncObj.Square(param)
      Console.Write("The result of calling sampSyncObj.Square with ")
      Console.WriteLine("{0} is {1}.", param, result)
      Console.WriteLine("")     

      Dim sampleDelegate As New SampSyncSqrDelegate(AddressOf sampSyncObj.Square)
      param = 8
      
      Console.WriteLine("Making a single asynchronous call on the context-bound object:")
      
      Dim ar1 As IAsyncResult = sampleDelegate.BeginInvoke(param, New AsyncCallback(AddressOf AsyncResultSample.MyCallback), param)
      
      Console.WriteLine("Waiting for the asynchronous call to complete...")
      Dim wh As WaitHandle = ar1.AsyncWaitHandle
      wh.WaitOne()
      
      Console.WriteLine("")
      Console.WriteLine("Waiting for the AsyncCallback to complete...")
      Thread.Sleep(1000)
   End Sub 'Main 
End Class 'AsyncResultSample 
using System;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;

// Context-bound type with the Synchronization context attribute.
[Synchronization()]
public class SampleSyncronized : ContextBoundObject {

    // A method that does some work, and returns the square of the given number.
    public int Square(int i)  {

        Console.Write("The hash of the thread executing ");
        Console.WriteLine("SampleSyncronized.Square is: {0}", 
                             Thread.CurrentThread.GetHashCode());
        return i*i;
    }
}

// The async delegate used to call a method with this signature asynchronously.
public delegate int SampSyncSqrDelegate(int i);

public class AsyncResultSample {

    // Asynchronous Callback method.
    public static void MyCallback(IAsyncResult ar) {

        // Obtains the last parameter of the delegate call.
        int value = Convert.ToInt32(ar.AsyncState);

        // Obtains return value from the delegate call using EndInvoke.
        AsyncResult aResult = (AsyncResult)ar;
        SampSyncSqrDelegate temp = (SampSyncSqrDelegate)aResult.AsyncDelegate;
        int result = temp.EndInvoke(ar);

        Console.Write("Simple.SomeMethod (AsyncCallback): Result of ");
        Console.WriteLine("{0} in SampleSynchronized.Square is {1} ", value, result);
    }

    public static void Main() {

        int result;
        int param;

        // Creates an instance of a context-bound type SampleSynchronized.
        SampleSyncronized sampSyncObj = new SampleSyncronized();

        // Checks whether the object is a proxy, since it is context-bound.
        if (RemotingServices.IsTransparentProxy(sampSyncObj))
            Console.WriteLine("sampSyncObj is a proxy.");
        else
            Console.WriteLine("sampSyncObj is NOT a proxy.");

        param = 10;

        Console.WriteLine("");
        Console.WriteLine("Making a synchronous call on the context-bound object:");

        result = sampSyncObj.Square(param);
        Console.Write("The result of calling sampSyncObj.Square with ");
        Console.WriteLine("{0} is {1}.", param, result);
        Console.WriteLine("");

        SampSyncSqrDelegate sampleDelegate = new SampSyncSqrDelegate(sampSyncObj.Square);
        param = 8;

        Console.WriteLine("Making a single asynchronous call on the context-bound object:");

        IAsyncResult ar1 = sampleDelegate.BeginInvoke( param, 
                              new AsyncCallback(AsyncResultSample.MyCallback), 
                              param);

        Console.WriteLine("Waiting for the asynchronous call to complete...");
        WaitHandle wh = ar1.AsyncWaitHandle;
        wh.WaitOne();

        Console.WriteLine("");
        Console.WriteLine("Waiting for the AsyncCallback to complete...");
        Thread.Sleep(1000);
    }
}
using namespace System;
using namespace System::Threading;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Contexts;
using namespace System::Runtime::Remoting::Messaging;

// Context-bound type with the Synchronization context attribute.

[Synchronization]
public ref class SampleSyncronized: public ContextBoundObject
{
public:

   // A method that does some work, and returns the square of the given number.
   int Square( int i )
   {
      Console::Write( "The hash of the thread executing " );
      Console::WriteLine( "SampleSyncronized::Square is: {0}", Thread::CurrentThread->GetHashCode() );
      return i * i;
   }

};

// The async delegate used to call a method with this signature asynchronously.
int i );
public ref class AsyncResultSample
{
public:

   // Asynchronous Callback method.
   static void MyCallback( IAsyncResult^ ar )
   {
      
      // Obtains the last parameter of the delegate call.
      int value = Convert::ToInt32( ar->AsyncState );
      
      // Obtains return value from the delegate call using EndInvoke.
      AsyncResult^ aResult = dynamic_cast<AsyncResult^>(ar);
      SampSyncSqrDelegate^ temp = static_cast<SampSyncSqrDelegate^>(aResult->AsyncDelegate);
      int result = temp->EndInvoke( ar );
      Console::Write( "Simple::SomeMethod (AsyncCallback): Result of " );
      Console::WriteLine( " {0} in SampleSynchronized::Square is {1} ", value, result );
   }

};

int main()
{
   int result;
   int param;
   
   // Creates an instance of a context-bound type SampleSynchronized.
   SampleSyncronized^ sampSyncObj = gcnew SampleSyncronized;
   
   // Checks whether the Object* is a proxy, since it is context-bound.
   if ( RemotingServices::IsTransparentProxy( sampSyncObj ) )
      Console::WriteLine( "sampSyncObj is a proxy." );
   else
      Console::WriteLine( "sampSyncObj is NOT a proxy." );

   
   param = 10;
   Console::WriteLine( "" );
   Console::WriteLine( "Making a synchronous call on the context-bound Object*:" );
   result = sampSyncObj->Square( param );
   Console::Write( "The result of calling sampSyncObj.Square with " );
   Console::WriteLine( " {0} is {1}.", param, result );
   Console::WriteLine( "" );
   
   SampSyncSqrDelegate^ sampleDelegate = gcnew SampSyncSqrDelegate( sampSyncObj, &SampleSyncronized::Square );
   param = 8;
   Console::WriteLine( "Making a single asynchronous call on the context-bound Object*:" );
   IAsyncResult^ ar1 = sampleDelegate->BeginInvoke( param, gcnew AsyncCallback( AsyncResultSample::MyCallback ), param );
   Console::WriteLine( "Waiting for the asynchronous call to complete..." );
   WaitHandle^ wh = ar1->AsyncWaitHandle;
   wh->WaitOne();
   Console::WriteLine( "" );
   Console::WriteLine( "Waiting for the AsyncCallback to complete..." );
   Thread::Sleep( 1000 );
   return 0;
   
}
import System.*;
import System.Threading.*;
import System.Runtime.Remoting.*;
import System.Runtime.Remoting.Contexts.*;
import System.Runtime.Remoting.Messaging.*;

// Context-bound type with the Synchronization context attribute.
/** @attribute Synchronization()
 */
public class SampleSyncronized extends ContextBoundObject
{
    // A method that does some work, and returns the square of the given number.
    public int Square(int i)
    {
        Console.Write("The hash of the thread executing ");
        Console.WriteLine("SampleSyncronized.Square is: {0}",
            (Int32)System.Threading.Thread.get_CurrentThread().GetHashCode());
        return i * i;
    } //Square
} //SampleSyncronized

// The async delegate used to call a method with this signature asynchronously.
/** @delegate 
 */
public delegate int SampSyncSqrDelegate(int i);

public class AsyncResultSample
{
    static int value;
    // Asynchronous Callback method.
    public static void MyCallback(IAsyncResult ar)
    {
        // Obtains the last parameter of the delegate call.
        SampSyncSqrDelegate sampDelg = (SampSyncSqrDelegate)ar.get_AsyncState();
        
        // Obtains return value from the delegate call using EndInvoke.
        AsyncResult aResult = (AsyncResult)ar;
        SampSyncSqrDelegate temp =
            (SampSyncSqrDelegate)(aResult.get_AsyncDelegate());
        int threadId = AppDomain.GetCurrentThreadId();
        int result = temp.EndInvoke(ar);

        Console.Write("Simple.SomeMethod (AsyncCallback): Result of ");
        Console.WriteLine("{0} in SampleSynchronized.Square is {1} ",
            (Int32)value, (Int32)result);
    } //MyCallback

    public static void main(String[] args)
    {
        int result;
        int param;
        // Creates an instance of a context-bound type SampleSynchronized.
        SampleSyncronized sampSyncObj = new SampleSyncronized();
        // Checks whether the object is a proxy, since it is context-bound.
        if (RemotingServices.IsTransparentProxy(sampSyncObj)) {
            Console.WriteLine("sampSyncObj is a proxy.");
        }
        else {
            Console.WriteLine("sampSyncObj is NOT a proxy.");
        }

        param = 10;
        Console.WriteLine("");
        Console.WriteLine("Making a synchronous call on the context-bound "
            + "object:");
        result = sampSyncObj.Square(param);
        Console.Write("The result of calling sampSyncObj.Square with ");
        Console.WriteLine("{0} is {1}.", (Int32)param, (Int32)result);
        Console.WriteLine("");

        SampSyncSqrDelegate sampleDelegate =
            new SampSyncSqrDelegate(sampSyncObj.Square);
        param = 8;
        value = param;
        Console.WriteLine("Making a single asynchronous call on the "
            + "context-bound object:");
        IAsyncResult ar1 = sampleDelegate.BeginInvoke(param,
            new AsyncCallback(AsyncResultSample.MyCallback), sampleDelegate);

        Console.WriteLine("Waiting for the asynchronous call to complete...");
        WaitHandle wh = ar1.get_AsyncWaitHandle();

        wh.WaitOne();
        Console.WriteLine("");
        Console.WriteLine("Waiting for the AsyncCallback to complete...");
        System.Threading.Thread.Sleep(1000);
    } //main 
} //AsyncResultSample

상속 계층 구조

System.Object
  System.Runtime.Remoting.Messaging.AsyncResult

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

참고 항목

참조

AsyncResult 멤버
System.Runtime.Remoting.Messaging 네임스페이스

기타 리소스

대리자를 사용한 비동기 프로그래밍