确定来自 UdpClient.Receive 的 SocketException 是否由超时引起

Determine if SocketException from UdpClient.Receive was caused by a timeout

我有一个 UdpClient 接收数据并设置了超时,例如:

UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 12345));
client.Client.ReceiveTimeout = 5000;     // 5 second timeout

while (!shutdown) {
    IPEndPoint source = null;
    byte[] data = client.Receive(ref source);  
}

Receivedocumented as throwing a SocketException if "an error occurred when accessing the socket". The behavior of setting ReceiveTimeout is also documented,因为如果同步操作超时则抛出 SocketException

如果在设置超时时从 Receive 得到 SocketException,我如何确定异常是由超时引起的而不是由更严重的错误引起的?

我确实确认超时抛出的异常是一个实际的 SocketException 而不是它的某个特定子类。我唯一能真正想到的是检查异常消息,这是一个我不太感兴趣的 hack。

您需要检查 SocketException.ErrorCode 属性 的值 10060 (WSATIMEDOUT)。

您可以在此处找到 ErrorCode 值的完整列表:https://docs.microsoft.com/windows/win32/winsock/windows-sockets-error-codes-2