0

I have a Windows Service which basically wraps a task:

public partial class Service : ServiceBase
{
    private Task task;
    private CancellationTokenSource cancelToken;

    public Service()
    {
        InitializeComponent();

        this.task = null;
        this.cancelToken = null;
    }

    protected override void OnStart(string[] args)
    {
        var svc = new MyServiceTask();
        this.cancelToken = new CancellationTokenSource();
        this.task = svc.RunAsync(cancelToken.Token);
        this.task.ContinueWith(t => this.OnUnhandledException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
    }

    protected override void OnStop()
    {
        if (this.task != null)
        {
            this.cancelToken.Cancel();
            this.task.Wait();
        }
    }

    private void OnUnhandledException(Exception ex)
    {
        this.EventLog.WriteEntry(string.Format("Unhandled exception: {0}", ex), EventLogEntryType.Error);
        this.task = null;
        this.Stop();
    }
}

As you can see, the service can catch unhandled exceptions. If this happens, the exception is logged and the service is stopped. This has the effect of writing two messages to the event log - one error stating there was an unhandled exception, and another stating that the service was successfully stopped.

This may sound minor, but I'm hoping to be able to suppress the 'successfully stopped' message. I find it misleading - it suggests that the service stopping was a normal occurrence. Is there another way I can force the service to stop itself without this message being logged?

Barguast
  • 5,926
  • 9
  • 43
  • 73
  • Sure; make the process crash, e.g., by raising a second exception and not bothering to catch that one. Or even just exit the process without telling the SCM that you're stopping, though IIRC that method doesn't trigger the service failure handling. – Harry Johnston Mar 28 '15 at 01:04
  • The problem is that if I rethrow an exception (in OnUnhandledException) then I'm pretty sure it'll not do anything until the task is awaited (only happens in Stop, and I'm pretty sure this causes it to simply refuse to stop). Exiting the process might work, I'll give that a go. – Barguast Mar 28 '15 at 10:34
  • All my services are unmanaged code. But there must be *some* way to make a .NET process crash. :-) If none of the .NET experts chip in, you could perhaps try raising a native exception by P/Invoking RaiseException. – Harry Johnston Mar 28 '15 at 22:54

0 Answers0