UdpClient.BeginReceive(AsyncCallback, Object) 메서드

정의

원격 호스트에서 데이터그램을 비동기적으로 수신합니다.

public:
 IAsyncResult ^ BeginReceive(AsyncCallback ^ requestCallback, System::Object ^ state);
public IAsyncResult BeginReceive(AsyncCallback? requestCallback, object? state);
public IAsyncResult BeginReceive(AsyncCallback requestCallback, object state);
member this.BeginReceive : AsyncCallback * obj -> IAsyncResult
Public Function BeginReceive (requestCallback As AsyncCallback, state As Object) As IAsyncResult

매개 변수

requestCallback
AsyncCallback

AsyncCallback 작업이 완료되면 호출할 메서드를 참조하는 대리자입니다.

state
Object

수신 작업에 대한 정보를 포함하는 사용자 정의 개체입니다. 작업이 완료되면 이 개체가 requestCallback 대리자에게 전달됩니다.

반품

IAsyncResult 비동기 수신을 참조하는 개체입니다.

예제

다음 코드 예제에서는 서버 응답을 비동기적으로 수신하는 데 사용합니다 BeginReceive .

public struct UdpState
{
    public UdpClient u;
    public IPEndPoint e;
}

public static bool messageReceived = false;

public static void ReceiveCallback(IAsyncResult ar)
{
    UdpClient u = ((UdpState)(ar.AsyncState)).u;
    IPEndPoint e = ((UdpState)(ar.AsyncState)).e;

    byte[] receiveBytes = u.EndReceive(ar, ref e);
    string receiveString = Encoding.ASCII.GetString(receiveBytes);

    Console.WriteLine($"Received: {receiveString}");
    messageReceived = true;
}

public static void ReceiveMessages()
{
    // Receive a message and write it to the console.
    IPEndPoint e = new IPEndPoint(IPAddress.Any, s_listenPort);
    UdpClient u = new UdpClient(e);

    UdpState s = new UdpState();
    s.e = e;
    s.u = u;

    Console.WriteLine("listening for messages");
    u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

    // Do some work while we wait for a message. For this example, we'll just sleep
    while (!messageReceived)
    {
        Thread.Sleep(100);
    }
}

설명

메서드를 호출 BeginReceive 하여 비동 EndReceive 기 작업을 완료해야 합니다. 일반적으로 메서드는 대리자가 호출합니다 requestCallback .

이 메서드는 작업이 완료될 때까지 차단되지 않습니다. 작업이 완료될 때까지 차단하려면 메서드를 Receive 사용합니다.

비동기 프로그래밍 모델 사용에 대한 자세한 내용은 동기 메서드를 비동기적으로 호출하는 방법을 참조하세요.

적용 대상