UdpClient.BeginReceive(AsyncCallback, Object) 方法

从远程主机异步接收数据报。

public IAsyncResult BeginReceive (AsyncCallback requestCallback, object state);

参数

requestCallback
AsyncCallback

一个 AsyncCallback 委托,它引用操作完成时要调用的方法。

state
Object

一个用户定义的对象,其中包含接收操作的相关信息。 当操作完成时,此对象会被传递给 requestCallback 委托。

返回

IAsyncResult

一个 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 方法。

有关使用异步编程模型的详细信息,请参阅 以异步方式调用同步方法

适用于

.NET

5.0 RC2

.NET Core

3.1 3.0 2.2 2.1 2.0

.NET Framework

4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5 3.0 2.0

.NET Standard

2.1 2.0

Xamarin.Android

7.1

Xamarin.iOS

10.8

Xamarin.Mac

3.0
原文地址:https://www.cnblogs.com/rainbow70626/p/13904338.html