c# - 在 Windows 服务中运行的线程中最终不执行

标签 c# timer windows-services try-catch-finally

谁能解释为什么这个 finally block 没有被执行?我读过关于何时期望 finally block 不被执行的帖子,但这似乎是另一种情况。此代码需要 TopShelf 和 log4net。我正在运行 .net 4.5

我猜一定是 Windows 服务引擎启动了未处理的异常,但为什么它在 finally block 完成之前运行?

using log4net;
using log4net.Config;
using System;
using System.Threading;
using Topshelf;

namespace ConsoleApplication1
{
    public class HostMain
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<HostMain>(s =>
                {
                    s.ConstructUsing(name => new HostMain());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });

                x.RunAsLocalSystem();
                x.SetServiceName("TimerTest");
            });
        }

        public void Stop()
        {
            LogManager.GetLogger("MyLog").Info("stopping");
        }

        public void Start()
        {
            XmlConfigurator.Configure();

            LogManager.GetLogger("MyLog").Info("starting");

            new Thread(StartServiceCode).Start();
        }

        public void StartServiceCode()
        {
            try
            {
                LogManager.GetLogger("MyLog").Info("throwing");

                throw new ApplicationException();
            }
            finally
            {
                LogManager.GetLogger("MyLog").Info("finally");
            }
        }
    }
}

输出

starting
throwing
stopping

编辑:请评论你为什么要降级,也许你不明白这个问题?我在这里看到一个大问题。您在 Exception 的 finally 子句中编写了一些域逻辑来做重要的事情。然后,如果您将逻辑托管在 Windows 服务中,设计就会突然崩溃。

最佳答案

来自 MDSN try-finally (C# Reference)

Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up. For more information, see Unhandled Exception Processing in the CLR.

Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important

这是设计使然,.NET 已选择终止您的应用程序,原因是出现了严重错误,某些事情没有按预期工作,通过调用 finally,我们不想造成更多损害,所以最好就是结束应用。

如果最终再抛出一个异常,它去哪儿了呢?如果应用程序即将关闭,它可能已经关闭或开始关闭托管资源,访问它们以最终登录也可能是致命的。

关于c# - 在 Windows 服务中运行的线程中最终不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31118912/

相关文章:

c# - 通过代码检索内置的 UI Sprite

networking - Net.exe在使用/savecred时使用 'Error: A command was used with conflicting switches.'

c# - Windows 服务中的无限 while 循环

c# - 可移动自定义控件

c# - 在后台运行应用程序 : Windows phone 8 phonegap

c# - 比较类型,包括 C# 中的基本类型

c - 使用C中的全局函数作为定时器?

jquery - 如何在jquery中使用不同的值多次调用函数

c# - 如何从网站上的表格中检索数据?