UdpClient.CancelReceive在哪里?

Rog*_*mbe 4 .net sockets

我正在实现一个简单的本地网络发现协议,所以我调用UdpClient.Send然后调用UdpClient.BeginReceive.如果有多个响应挂起,我会在回调结束时调用UdpClient.BeginReceive.像这样的东西:

UdpClient client = new UdpClient(AddressFamily.InterNetwork);
client.EnableBroadcast = true;
client.Send(request, request.Length, broadcastEndPoint);
client.BeginReceive(Callback, client);
Run Code Online (Sandbox Code Playgroud)

......然后在Callback:

void Callback(IAsyncResult ar)
{
    UdpClient client = (UdpClient)ar.AsyncState;
    IPEndPoint remoteEndPoint = null;
    byte[] response = client.EndReceive(ar, ref remoteEndPoint);

    // Do something with response

    client.BeginReceive(Callback, client);
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我的主循环调用,client.Close而仍然有一个待处理的接收.接收完成,然后我对BeginReceive的下一次调用抛出异常:System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

为什么UdpClient没有CancelReceive方法?我该怎么做?

小智 6

相反或要克服此异常创建bool并在发出close命令之前设置它,使用该bool检入回调

像这样

bool isClosing=false;
void Callback(IAsyncResult ar)
{
    if(isClosing) return;
}
Run Code Online (Sandbox Code Playgroud)

bool isClosing发出close命令之前设置