我想知道我是否可以为UdpClient接收方法设置超时值.
我想使用块模式,但因为有时udp会丢失数据包,我的程序udpClient.receive将永远挂在那里.
我有什么好主意可以管理它?
有一个SendTimeout
和一个ReceiveTimeout
属性,你可以使用Socket
的UdpClient
.
以下是5秒超时的示例:
var udpClient = new UdpClient(); udpClient.Client.SendTimeout = 5000; udpClient.Client.ReceiveTimeout = 5000; ...
Filip所指的是嵌套在UdpClient
包含(UdpClient.Client.ReceiveTimeout
)的套接字中.
您也可以使用异步方法执行此操作,但手动阻止执行:
var timeToWait = TimeSpan.FromSeconds(10); var udpClient = new UdpClient( portNumber ); var asyncResult = udpClient.BeginReceive( null, null ); asyncResult.AsyncWaitHandle.WaitOne( timeToWait ); if (asyncResult.IsCompleted) { try { IPEndPoint remoteEP = null; byte[] receivedData = udpClient.EndReceive( asyncResult, ref remoteEP ); // EndReceive worked and we have received data and remote endpoint } catch (Exception ex) { // EndReceive failed and we ended up here } } else { // The operation wasn't completed before the timeout and we're off the hook }