我正在使用 Visual Studio 2017。
每当我按 F5
开始调试我的程序时,我注意到 Program
类中的 Main(string[] args)
方法不被调用,即使 Program
中的字段已初始化,如下面的屏幕截图所示:
在创建一个 TcpClient
实例并将其分配给相应的字段后,调试器从未命中我在 Main(string[] args)
方法上设置的断点.
可以肯定的是,我已将项目的启动对象设置为 Program
类。这并没有解决问题:
我错过了什么?
编辑:
我在 Main
方法中添加了 Console.WriteLine("Entering Main method...")
,但是当我开始调试时它没有打印到控制台.
在创建 TcpClient
实例之后,几乎没有任何事情(或者更确切地说,没有立即可见的事情)发生——没有抛出异常;该程序不会自行终止;控制台保持空白。
编辑:
结果是 TcpClient
构造函数内部发生了崩溃。
最佳答案
请记住,TcpClient(string, int)
构造函数会打开一个新连接,此时 (doc):
Initializes a new instance of the TcpClient class and connects to the specified port on the specified host.
...
This constructor creates a new TcpClient and makes a synchronous connection attempt to the provided host name and port number.
如果我复制/粘贴您的代码(插入我自己的 RemoteServerIpAddressString
),然后我看到应用程序在尝试构建 TcpClient
时挂起。如果我此时中断调试器,我可以看到它卡在 System.Net.Sockets.Socket.DoConnect
中,它正在尝试连接到远程机器。
一段时间后它放弃,抛出异常,并抛出 TypeInitializationException
,这会破坏调试器。
这符合您的观察:
Literally nothing (or rather, nothing immediately visible) happens after the TcpClient instance is created -- no exceptions thrown; the program doesn't self-terminate; the console stays blank.
此时,TcpClient
仍在尝试连接。在它成功之前,该类型永远不会被初始化,并且在这发生之前 Main
永远不会运行。如果放置时间足够长,它可能会失败,就像我的一样。
如果我确定 TcpClient
正在连接到一个打开的端口,那么 TcpClient
构造函数会立即完成并运行 Main
.
在静态构造函数中做长时间运行的事情——尤其是与网络有关的事情——是一个非常糟糕的主意。 CLR 需要在初始化一个类型时获取锁,这会阻止其他类型的初始化,并可能导致死锁。
您可能想在 Main
方法中构造 TcpClient
,或者将其构造为:
private static readonly TcpClient TcpClient = new TcpClient();
然后在主要部分:
TcpClient.Connect(...);
关于c# - 未调用 Main(string[] args) 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55494761/