1

I am having MSMQ on windows 2008. Messages are available in private queue. I have one WCF subscriber (written in C#) which is installed as windows service. Now problem is that sometimes the WCF subscriber stops picking messages from Queue. If I restart service again it works fine. Now I attached IError Handler to log the reason and exception.

Now to Handle this issue what I wanted to do is, I will set the recovery property to restart service on first failure and now problem is how to throw the error from HandleError() method of IErrorHandler class?

Please tell me best way to throw an exception in a window service so it can be restarted.

tom redfern
  • 30,562
  • 14
  • 91
  • 126
samash
  • 757
  • 2
  • 15
  • 32
  • First of all you should find out why the service stops picking messages - that is the problem. Maybe you should describe this situation and ask about that? – Tadas Šukys May 21 '13 at 18:29
  • @TadasŠukys- I have No clue why its suddenly stops picking message from queue.still window service is running, when i go to stop the window service then it throws the error and from windows log error is:Failed to stop service. System.ServiceModel.CommunicationObjectFaultedException: The communication object, System.ServiceModel.ServiceHost, cannot be used for communication because it is in the Faulted state. at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout) at Microsoft.Samples.MSMQToWCF.SubscriberWindowsService.OnStop() in d:\SubscriberWindowsService – samash May 22 '13 at 05:23
  • @samash see http://stackoverflow.com/questions/4197036/what-is-the-proper-way-for-a-windows-service-to-fail – stuartd May 22 '13 at 08:54

2 Answers2

1

While it is probably better to address the underlying cause of your exceptions, it is certainly valid in certain scenarios to implement a fail fast methodology. Indeed, this ability to kill processes which have become "flawed" in some manner is critical to the concept of fault tolerance.

So, to make a windows service commit suicide:

void KillSelf()
{
    try
    {
        // Code to close open connections/dispose 
        // of unmanaged resources etc
        ...
    }
    finally
    {
        Environment.Exit(1);
    }
}

Service recovery options should be set to restart automatically. This will ensure your service comes straight back up again.

tom redfern
  • 30,562
  • 14
  • 91
  • 126
0

As far as I know one cannot throw an exception to restart a windows service.

I usually encapsulate a try catch (with logging) to prevent any exceptions crashing the service, which is the opposite to what you are suggesting.

It may be that you can catch an error and stop the service (not sure) and configure the service to restart if it stops?

Mark Redman
  • 24,079
  • 20
  • 92
  • 147