Windows 服务刚刚停止.没有消息,没有警报,错误,警告 - 什么都没有 [英] Windows Service just stops. No messages, no alerts, errors, warning - nothing

查看:39
本文介绍了Windows 服务刚刚停止.没有消息,没有警报,错误,警告 - 什么都没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Windows 服务,它会自行停止.相关代码如下:

I have a Windows service that just silently stops on its own. Here is the relevant code:

OnStart() 方法:

OnStart() method:

    protected override void OnStart(string[] args)
    {
        try
        {
            InitializeLogging();

            // we don't DO command line arguments
            if (args.Length > 0)
            {
                eventLog.WriteEntry("All command line arguments are ignored.  You must edit the app.config file manually to make changes to what watchers are run.");
                throw new ArgumentException("Command line arguments are ignored.");
            }

            ReadAppConfig();
            RecalculateStartTimes();
            InitializeWatchers();

        }
        catch (Exception e)
        {
            eventLog.WriteFormattedEntry("Error on Start: {0}", e.Message);
        }
        finally
        {
            eventLog.WriteEntry("Service start completed");
        }
    }

OnStop() 方法:

OnStop() method:

    protected override void OnStop()
    {
        eventLog.WriteEntry("Service stopped.");
    }

InitializeWatchers() 方法:

InitializeWatchers() method:

    private void InitializeWatchers()
    {
        try
        {

            var watchers = _watcherSection.Watchers.ToList<WatcherElement>();

            eventLog.WriteEntry(string.Format("Initializing {0} watchers.", watchers.Count()));

            var obsWatchers = watchers.ToObservable();
            obsWatchers.SelectMany(
                watcher =>
                    Observable.Timer(watcher.StartTime, TimeSpan.FromHours(watcher.Interval))
                              .SelectMany(
                                    Observable.FromAsync(
                                      async () => new
                                      {
                                          watcher,
                                          response = await CheckFolder(watcher.Path)
                                      })))
                              .Subscribe(
                                    onNext: x =>
                                    {
                                        eventLog.WriteFormattedEntry("\nWatcher: {0}, Time:{1}", x.watcher.Name, DateTimeOffset.Now);
                                        if (x.response.Success)
                                            eventLog.WriteFormattedEntry("| Success!\n| Value: '{0}'\n| Message: {0}", x.response.Value, x.response.Message);
                                        else
                                            eventLog.WriteFormattedEntry("| FAILURE!\n| Value: '{0}'\n| Message: {0}\n| Errors: '{0}'", x.response.Value, x.response.Message, x.response.Exceptions.First());
                                    },
                                    onError: e =>
                                        {
                                            var err = e;
                                            var sb = new StringBuilder();
                                            sb.AppendLine("The observer threw an error:")
                                              .AppendFormatLine("| Message: {0}", e.Message);

                                            while (e.InnerException != null)
                                            {
                                                sb.AppendFormatLine("| Inner: {0}", e.InnerException.Message);
                                                e = e.InnerException;
                                            }

                                            sb.AppendLine();
                                            eventLog.WriteEntry(sb.ToString());
                                            throw err;
                                        });

            eventLog.WriteEntry("about to wait.");
            obsWatchers.Wait();
            eventLog.WriteEntry("passed the wait");
        }
        catch (Exception e)
        {
            eventLog.WriteFormattedEntry("Exception thrown in InitializeWatchers(WatchersSection): {0}", e.Message);
            throw;
        }
    }

当我运行这段代码时,服务正常启动.事件日志记录了三个事件:

When I run this code, the service starts normally. The event log records three events:

  1. 服务与日志记录开始.
  2. 初始化 1 个观察者.
  3. 服务启动完成.

...它停止了.我必须手动刷新服务"窗口,但它停止运行.我没有收到任何错误或任何其他 eventLog 条目.

... and it stops. I have to manually refresh the Services window, but it quits running. I don't get any errors, or any of the other eventLog entries.

令人沮丧的是,这段代码可以完美地作为控制台应用程序运行.我已将所有 eventLog.WriteEntry() 更改为 Console.WriteLine(),但除此之外,代码完全相同并按预期执行.

The frustrating thing is that this code works perfectly as a Console app. I've changed all the eventLog.WriteEntry() to Console.WriteLine(), but other than that, the code is identical and performs as expected.

任何智慧将不胜感激.

推荐答案

与其使用 obsWatchers.Wait() 阻止并导致斯蒂芬所说的问题,不如异步订阅.

Instead of using obsWatchers.Wait() which blocks and causes the problems Stephen has said, just asynchronously subscribe.

将此属性添加到您的类:

Add this property to your class:

private SingleAssignmentDisposable _subscription = new SingleAssignmentDisposable();

将此添加到您的 OnStop 方法中:

Add this to your OnStop method:

_subscription.Dispose();

在您的 InitializeWatchers() 中,消除对 Subscribe 的嵌套调用,并将 obsWatchers.Wait() 替换为订阅调用,例如所以:

In your InitializeWatchers(), eliminate the nested call to Subscribe and replace obsWatchers.Wait() with a call to subscribe, like so:

private void InitializeWatchers()
{
    try
    {

        var watchers = _watcherSection.Watchers.ToList<WatcherElement>();

        eventLog.WriteEntry(string.Format("Initializing {0} watchers.", watchers.Count()));

        var obsWatchers = watchers.ToObservable();
        _subscription.Disposable = obsWatchers
            .SelectMany(watcher => Observable
                .Timer(watcher.StartTime, TimeSpan.FromHours(watcher.Interval))
                .SelectMany(_ => Observable.FromAsync(async () => new
                      {
                          watcher,
                          response = await CheckFolder(watcher.Path)
                      })))
             .Subscribe(
                 onNext: x =>
                 {
                     eventLog.WriteFormattedEntry("\nWatcher: {0}, Time:{1}", x.watcher.Name, DateTimeOffset.Now);
                     if (x.response.Success)
                         eventLog.WriteFormattedEntry("| Success!\n| Value: '{0}'\n| Message: {0}", x.response.Value, x.response.Message);
                     else
                         eventLog.WriteFormattedEntry("| FAILURE!\n| Value: '{0}'\n| Message: {0}\n| Errors: '{0}'", x.response.Value, x.response.Message, x.response.Exceptions.First());
                 },
                 onError: e =>
                 {
                     var err = e;
                     var sb = new StringBuilder();
                     sb.AppendLine("The observer threw an error:")
                       .AppendFormatLine("| Message: {0}", e.Message);

                     while (e.InnerException != null)
                     {
                         sb.AppendFormatLine("| Inner: {0}", e.InnerException.Message);
                         e = e.InnerException;
                     }

                     sb.AppendLine();
                     eventLog.WriteEntry(sb.ToString());
                     throw err;
                 });
        eventLog.WriteEntry("passed the wait");
    }
    catch (Exception e)
    {
        eventLog.WriteFormattedEntry("Exception thrown in InitializeWatchers(WatchersSection): {0}", e.Message);
        throw;
    }
}

这篇关于Windows 服务刚刚停止.没有消息,没有警报,错误,警告 - 什么都没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆