防止 TcpClient.Connect 的第一次机会异常

Prevent First Chance Exception for TcpClient.Connect

我的代码中有一条非常令人沮丧的 First Chance Exception 消息。

A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll Additional information: No connection could be made because the target machine actively refused it"

private void RunThread()
{
    do
    {
        TcpClient client = null;
        StreamWriter writer = null;

        try
        {
            // Connect
            client = new TcpClient();
            client.Connect(m_Hostname, m_PortNum);

            if (client.Connected) //No host available? EXCEPTION!
            {
                //Do stuff and exit listener thread
            }


        }
        catch (Exception e)
        {
            //dont care
        }
    } 
}

现在简单解释一下。有问题的代码位于线程中

1) 这是一个可以忽略的错误!我们可以继续。但问题是我必须禁用第一次机会异常(其他人也是如此)才能让应用程序继续。

2) 好的,假设我们禁用了错误。那很好,但是因为我们在一个线程中并且 运行 不断地进入异常。我们明白了。当想要查看调试 window.

时,这变得非常烦人

A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll

问题

  1. 我可以在不抛出异常的情况下轮询目标主机吗?

  2. 如果没有,我可以禁用这个断言吗?有解决办法吗?

您是否尝试过 DebuggerNonUserCode 属性? https://msdn.microsoft.com/en-us/library/system.diagnostics.debuggernonusercodeattribute.aspx 它应该阻止调试器单步执行该方法,这样您就不会收到通知。