I'm running Win 7 Pro 64-bit. I wrote a service in C# using the .NET 4 framework. It installs properly and starts to run. I know that it runs because it writes some output to a log file. However, after a few seconds it dies. When I use Visual Studio 2010 Pro to run this same code not as a service it never dies. So, my obvious question is regarding the appropriate approach for debugging this since I can't figure out why it should die as a service but not die as a non-service. I've put writes to the log file in several places in the code but it seems to die in a different place every time. The application has 3 threads. Any suggestions are welcomed.
-
Does your Windows Event log say anything? – keyboardP May 11 '11 at 23:39
-
Does the same thread die first every time? – soandos May 11 '11 at 23:40
-
2Is your logic in the "Start()" method? – Reed Copsey May 11 '11 at 23:55
2 Answers
If you're running your code directly from within the Service's Start method, this behavior can easily occur. The problem is that the service's Start method is expected to start the service and immediately return. If it sits there executing code, Windows will kill the service on you.
The correct way to handle this is to have the service's Start() method run your code in a dedicated thread. It shouldn't really need anything except the thread creation and an immediate return. If this is the problem, just setup a foreground thread and put your logic there, and it will likely work correctly.

- 554,122
- 78
- 1,158
- 1,373
Use System.Diagnostics.Debugger.Launch
to run it as a service and debug. If it doesn't crash in that scenario add additional logging and make sure to add a top level catch to write out any error. If that still doesn't do it create a crashdump file and examine with with SOS and windbg.

- 25,014
- 6
- 48
- 78