Try/Catch、Windows 服务和 Environment.Exit

Try/Catch, Windows Service and Environment.Exit

我在 Windows Azure Server 2012 R2 VM 上的 windows 服务应用程序中发现了非常有趣的行为。我的 windows 调用的服务,

ThreadPool.QueueUserWorkItem((_) => DoWork());

在 DoWork 中,

    private static void DoWork()
    {
        try
        {
            // Do all work
            Environment.Exit(0);
        }
        catch (Exception ex)
        {
            Logger.Log(ex);
        }
    }

Environment.Exit(0) 的调用导致进程崩溃。没有登录事件查看器,也没有更多信息。就 process unexpectedly terminated。为什么 try/catch 在那里不起作用?这是 Windows 服务应用程序的预期行为吗?

Why try/catch is not working there?

根据MSDN

If Exit is called from a try or finally block, the code in any catch block does not execute.

@RufusL 说的对,您不应该那样关闭您的应用程序。

也许有更优雅的关闭应用程序的方式。 比如,也许,调用一个关闭事件或者你可以尝试删除那个 Environment.Exit(0) 代码和 'let things be' :D