UdpClient.BeginReceive(AsyncCallback, Object) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
从远程主机异步接收数据报。
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 方法。
有关使用异步编程模型的详细信息,请参阅 异步调用同步方法。