c# - 未调用 Main(string[] args) 方法

标签 c# visual-studio visual-studio-2017

我正在使用 Visual Studio 2017。

每当我按 F5 开始调试我的程序时,我注意到 Program 类中的 Main(string[] args) 方法不被调用,即使 Program 中的字段已初始化,如下面的屏幕截图所示:

enter image description here

在创建一个 TcpClient 实例并将其分配给相应的字段后,调试器从未命中我在 Main(string[] args) 方法上设置的断点.

可以肯定的是,我已将项目的启动对象设置为 Program 类。这并没有解决问题:

enter image description here

我错过了什么?

编辑:

我在 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/

相关文章:

c# - 为什么在使用对象远程处理 MarshalByRefObj 时使用委托(delegate)?

c# - 如何在不使用模型的情况下使用 Entity Framework 执行原始 SQL 查询?

c# - 如何检查字符数组中是否存在特定字符

c# - 如何使用 MSBuild 注册一个 dll

c++ - GDI+ 库导致 "error C2760: syntax error: unexpected token ' 标识符',在 VS2017 中为 XP 编译时预期为 'type specifier'"

c# - 抛出错误但不向用户显示错误的最简洁方法(没有自定义错误页面)

c++ - Visual Studio 调试持续未处理的异常

c# - CA2101 外部调用警告

git - 有没有办法通过 VS IDE 将我未提交的源代码与 git 中的任意历史记录项进行比较?

asp.net-core - 如何更新 Microsoft.AspNetCore?