【发布时间】:2015-09-16 02:34:19
【问题描述】:
谁能解释为什么这个 finally 块没有被执行?我已经阅读了有关何时期望 finally 块不被执行的帖子,但这似乎是另一种情况。此代码需要 TopShelf 和 log4net。我正在运行 .net 4.5
我猜一定是 Windows 服务引擎启动了未处理的异常,但为什么它在 finally 块完成之前运行?
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
编辑:请评论您降级的原因,也许您不明白问题所在?我在这里看到了一个大问题。你在异常的 finally 子句中编写了一些域逻辑来做重要的事情。然后,如果您将逻辑托管在 Windows 服务中,则设计会突然中断。
【问题讨论】:
-
你怎么知道它没有执行?您是否尝试过单步执行代码?
-
日志记录告诉我,如果您使用调试器,也是如此。
-
它是否进入 finally 块 - 所以不执行。或者可能是不记录的问题。
-
工作线程中的异常会无条件地终止您的应用程序。不为 AppDomain.CurrentDomain.UnhandledException 编写事件处理程序绝不是错误。
-
恕我直言,它与 CurrentDomain.UnhandledException 无关。如果我添加这样,这将被执行,但这并不能解释为什么 finally 块没有被执行。
标签: c# timer windows-services try-catch-finally