我正在编写一个 ServerLocator,它基本上广播一个端口来查找将使用 IPEndPoint 进行响应的服务器,并且如果在当前 IPHost 上找不到任何内容,我需要搜索能够超时,然后继续进行下一个。
现在我正在做这样的事情(我已经删除了这段代码的某些部分,因此它只包含显示我的问题所需的内容。这里还有一些客户端绑定)
string serverIp = string.Empty;
while(string.isNullOrEmpty(serverIp))
{
foreach (IPAddress adress in ipHosts.AddressList)
{
using(Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
{
try
{
client.ReceiveFrom(buffer, ref tempRemoteEP);
//Get server IP
serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
break;
}
catch(SocketException e)
{
// We expect connection attempt to time out if we cant find any server on this port and nic. Just continue with the next
if (e.SocketErrorCode == SocketError.TimedOut)
{
continue;
}
}
}
}
}
这按预期工作,除了控制台收到垃圾邮件:
System.dll 中发生“System.Net.Sockets.SocketException”类型的第一次机会异常
有没有一种好的方法可以处理这样的异常而不向控制台发送垃圾邮件?或者我可以用其他方式处理这个问题以避免超时异常吗?
Thanks.
如果程序继续运行的话,真的不需要担心这个,程序中会发送很多这样的异常。看本文 http://blogs.msdn.com/b/davidklinems/archive/2005/07/12/438061.aspx有关“首次例外”的更多信息。
另请检查这个链接 http://www.unittesting.com/documentation/tips/BreakOnThrow.html查看如何配置 Visual Studio 来处理异常。如果您配置了这些,您可以在异常时中断(而不是继续)并查看到底发生了什么。但是,请注意,隐藏异常似乎在调试中不起作用,请参阅here https://stackoverflow.com/questions/1357096/how-can-i-hide-an-exception-type-from-the-output-window-in-visual-studio or here https://stackoverflow.com/questions/58380/avoiding-first-chance-exception-messages-when-the-exception-is-safely-handled但正如 @Cipi 指出的那样,它不应该在发布中可见。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)