【发布时间】:2014-02-10 10:48:47
【问题描述】:
在启动我的 Windows 服务时不断遇到此错误消息。
本地计算机上的服务启动然后停止。如果某些服务没有被其他服务和程序使用,它们会自动停止。
我的代码:
protected override void OnStart(string[] args)
{
string eventLogMessage = string.Format(@"Notify Service is starting :{0}", DateTime.Now);
EventLogging.LogInformation(eventLogMessage);
double interval;
try
{
interval = Convert.ToDouble(ConfigurationManager.AppSettings["intervalInSeconds"]);
EventLogging.LogInformation(
string.Format("Loaded configuration: Interval duration is {0} minutes", (interval / 60)));
}
catch (Exception exception)
{
interval = 3600;
eventLogMessage = string.Format("Loading configuration failed: Interval duration is {0} minutes", (interval / 60));
eventLogMessage += string.Format("\nMessage was: {0}", exception.Message);
EventLogging.LogWarning(eventLogMessage);
}
interval = interval * 1000;
_timer.Interval = interval;
_timer.Elapsed += TimerTick;
_timer.Start();
eventLogMessage = string.Format(@"Notify service has started: {0}", DateTime.Now);
EventLogging.LogInformation(eventLogMessage);
var workerThread = new Thread(NotifyUsers) { IsBackground = true };
workerThread.Start();
}
private void NotifyUsers()
{
var userBL = new UserBL();
List<User> usersToBeMailed = userBL.GetAllUsersWhosePasswordsWillExpire();
string eventLogMessage = string.Format("Number of users to be mailed is {0}", usersToBeMailed.Count);
EventLogging.LogInformation(eventLogMessage);
foreach (User user in usersToBeMailed)
{
userBL.MailUser(user);
}
}
private void TimerTick(object sender, ElapsedEventArgs e)
{
var workerThread = new Thread(NotifyUsers) { IsBackground = true };
workerThread.Start();
}
protected override void OnStop()
{
base.OnStop();
string eventLogMessage = @"Password notify service has stopped: " + DateTime.Now;
EventLogging.LogInformation(eventLogMessage);
}
protected override void OnPause()
{
base.OnPause();
_timer.Stop();
EventLogging.LogWarning("Paused");
}
protected override void OnContinue()
{
base.OnContinue();
_timer.Start();
EventLogging.LogInformation("Resumed");
}
}
【问题讨论】:
-
对于
OnStart`OnStop` 方法的内容有相当严格的规定。我猜是workerThread代码。作为测试尝试删除它,看看它是否仍然停止。 -
还将 _timer 和 worker 移至单独的“初始化”方法。
OnStart应该很简单,具有完整的异常处理。 -
尝试将调试器附加到服务以查找发生异常的位置,在 OnStart() 方法的第一行添加 Thread.Sleep(30000) 以便您有时间附加代码完成执行之前的调试器。不要忘记调用 Thread.Sleep 后的断点,这样你可以在线程唤醒时手动逐行调试。
-
您可能会在 windows 日志中找到一些有用的信息。在事件查看器上打开 MMC,导航到 Windows 日志-> 应用程序。通常你会在那里发现一些抛出的异常。
标签: c# windows-services