7

我正在为 Windows 任务调度程序编写一个控制台程序来运行。我的Main()方法的返回类型为int,退出时返回不同的数字以指示执行结果,我可以在.BAT脚本中以%errorlevel%.

但是在 VS2015 中调试时,我做了一个

return 255;

我总是从 VS2015 的输出窗口中得到:

The program '[43560] Foo.vshost.exe' has exited with code 0 (0x0).

现在,如果我希望输出窗口显示我的程序的退出代码,我必须Application.Exit(255)为它显示

The program '[24400] Foo.vshost.exe' has exited with code 255 (0xff).

奇怪的是%errorlevel%,如果我CMD.exe使用 return 语句或Environment.Exit().

所以我的问题是

  1. 的返回值是否与Main()有所不同Environment.ExitCode

  2. Main()VS2015有什么方法可以轻松找出方法的返回值?

  3. 退出控制台程序时,是否Environment.Exit()比简单的返回语句更受欢迎?因为退货声明更符合我的口味。

有人能告诉我这背后的故事吗?谢谢。

4

1 回答 1

7

Main() 的返回值与 Environment.ExitCode 是否有些不同?

不,他们是一样的,去同一个地方。您可以通过尝试仅返回 -1 或设置Environment.ExitCode为 -1 的控制台应用程序来看到这一点。您将看到您使用的任何方法都可以正常工作并%ERRORLEVEL%正确设置。

VS2015有什么方法可以轻松找出Main()方法的返回值?

首先,简要介绍一下似乎正在发生的事情。这是使用默认项目设置创建的控制台应用程序的堆栈跟踪:

TestApp.exe!TestApp.Program.Main(string[] args)
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args)
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state)
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart()

请注意,VS 主机进程在那里。禁用 VS 托管进程后,堆栈跟踪(使用相同的选项)如下所示:

TestApp.exe!TestApp.Program.Main(string[] args)

如果您查看参考源ThreadHelper.ThreadStart中的定义,您会看到它定义为:

internal void ThreadStart(object obj)

似乎这个 void 返回被用作进程返回值,或者上面的其他方法之一正在消耗返回值并吞下它。

如果您更改项目配置并禁用托管过程,那么您将获得如下输出:

The program '[7992] TestApp.exe' has exited with code -1 (0xffffffff).

如你所料。要禁用托管进程,请转到项目属性,然后在调试选项卡上,取消选中“启用 Visual Studio 托管进程”

退出控制台程序时,Environment.Exit() 是否比简单的 return 语句更受欢迎?因为退货声明更符合我的口味。

无论您喜欢哪个。正如 Jeppe Stig 在评论中指出的那样,有关差异的更多信息,请参阅文档Environment.Exit

于 2016-06-13T12:40:15.067 回答