[英]Changing a source file to compile Main() method in a project, in VS c# console application
[英]C# console application: Main method return value VS Application.ExitCode
我正在為Windows任務調度程序編寫一個控制台程序來運行。 我的Main()
方法的返回類型為int
並且在退出時返回不同的數字以指示執行結果,我可以在.BAT
腳本中以%errorlevel%
。
但是在VS2015中進行調試時,我會做一個
return 255;
我總是從VS2015的輸出窗口獲取:
The program '[43560] Foo.vshost.exe' has exited with code 0 (0x0).
現在如果我想讓Output窗口顯示我程序的退出代碼,我必須做一個Application.Exit(255)
來顯示它
The program '[24400] Foo.vshost.exe' has exited with code 255 (0xff).
奇怪的是,如果我使用return語句或Environment.Exit()
在CMD.exe
運行程序,則%errorlevel%
被正確設置為255。
所以我的問題是
Main()
的返回值是否與Environment.ExitCode
有些不同?
在VS2015中輕松找出Main()
方法的返回值的方法是什么?
退出控制台程序時, Environment.Exit()
比簡單的return語句更受歡迎? 因為回報聲明更符合我的口味。
有人能告訴我這背后的故事嗎? 謝謝。
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
的文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.