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 该方法。

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

适用于