我可以在C#中为UdpClient设置超时吗? [英] Can I set the timeout for UdpClient in C#?
本文介绍了我可以在C#中为UdpClient设置超时吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否可以为UdpClient的接收方法设置超时值。
I am wondering whether I can set a timeout value for UdpClient receive method.
我想使用块模式,但是因为有时udp会丢失数据包,所以我的程序
I want to use block mode, but because sometimes udp will lost packet, my program udpClient.receive will hang there forever.
我该如何管理它的任何好主意?
any good ideas how I can manage that?
推荐答案
Filip所指的内容嵌套在 UdpClient
所包含的套接字内( UdpClient.Client.ReceiveTimeout
)。
What Filip is referring to is nested within the socket that UdpClient
contains (UdpClient.Client.ReceiveTimeout
).
您也可以使用异步方法来执行此操作,但要手动阻止执行:
You can also use the async methods to do this, but manually block execution:
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
}
这篇关于我可以在C#中为UdpClient设置超时吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文