I am trying to a Window Service in C#, which should be running always. If there is a crash or shutdown, then it should automatically restart. I considered using Service controller class, but the problem is how to handle if both Service Controller & Service go down at same time.
Is there a watchdog functionality in Windows with which I can register and it takes care of the service start up?
You could consider using recovery options of service. It can be set through properties of the service when running services.msc.
Please look here and here for more information.
Adding to the above recommended pattern, probably it's a good idea to
Catch the unhandled exception by subscribing to the appdomain.unhandledexception event.
And unload the application domain so that the windows service manager will
initiate the recovery procedure.
AppDoamin.currentAppDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Environment.Exit(-1);
}
One recommended pattern here is to set the service start up options to 'Auto' and also, ensure the core functionality of your service is wrapped in a try/catch block.
try
{
// core code here.
}
catch (Exception ex)
{
// log it for debugging and swallow so that service doesn't crash.
}
this ensures that your service is always running. the code will not crash it, and when the machine reboots etc., the service is auto started.
Related
I am using visual studio professional 2015, c# .net framework 4.
I have created a service for windows that sends and receives data on the serial port. It is intended to start when the computer starts and shutdown when the computer is shutdown. It should not hang or stop otherwise.
I have been running tests and find that when windows does an update it causes my service to hang. I have no idea how to debug this hang.
I would appreciate any ideas on how to start tracking down this bug.
thanks.
Here's something that might help.
When I write a service, I typically add an event handler to this AppDomain event called UnhandledException.
It's sort of a catch-all exception handler and has come in handy on a number of occassions and helps you improve your error handling, in general.
// Add this code to the Service Start method or the constructor
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// Then add this method to your service class, it will be invoked when
// your code encounters an exception that is not trapped by a try/catch/finally
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception;
Trace.TraceError("Unhandled Exception occurred in service: {0}", ex);
}
Feel free to replace the Trace logging with your own logging framework if necessary.
Hope this helps.
I have created a windows service to send mail when service is started. The service works fine like it sends mail when i debug the service and run it via code. But the service is not working after i install it. It is not sending any mail after i install the service.
Can anyone please suggest me the solution?
There is an excellent chance that the service lacks permission to perform one or more actions when run as a service account.
Check the Windows Event Log for any related error messages. As a test, you can configure your service to run as the same user you log on with (just to make sure the issue is permission based... do NOT leave that configuration active as it is a major security hole).
Debugging service is a bit difficult.
use try..catch block with writing messages to file in every method; for example
try
{
..
}
catch(Exception ex)
{
SaveMessage(ex.ToString());
}
Save message method would be:
static void SaveMessage(string s)
{
StreamWriter sw = new StreamWriter(#"C:\service_exceptions_file.txt", true);
sw.WriteLine(s);
sw.Close();
}
Then you will see where is the problem.
Also you can add some messages in your code via abovementioned method to see what parts of code are working without problems
In your Main() method, just add the following lines before ServiceBase.Run(ServicesToRun); :
#if DEBUG
while(!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
#endif
Then install your service and launch it.
While it's launching, attach your debugger to your service's process (Debug Menu => Attach to process) and you should be able to debug it.
Don't forget to set your breakpoints before launching your service.
I am fairly new to Windows services. I created an installer for my c# Windows service and the installation on the server (Windows Server 2003) appears to have worked. When it's started, it writes Service started successfully to the log. When it's stopped, it writes Service stopped successfully. However, sometimes the service stops running without writing anything to the log, so I start it back up manually. When I look at the log afterward, it says Service started successfully as expected. It's weird seeing that in the log twice in a row being that it's obviously missing an entry where the service had somehow stopped running.
What could be the potential causes for this? I have the service set up as automatic and installed it to run for all users. I was under the impression that this means the service starts automatically whenever the machine boots up. How can I find out why it stopped? Do services that crash automatically write to the event log or do I have to handle exceptions in such a way that they log their own reason for the crash?
Edit: Some additional info:
I have it set up to log on as Local System Account
Under Recovery options, I have it set up to restart on first failure. I don't have anything for second or subsequent failures.
Update: An answerer recommended a global exception handler. While I won't implement this as a permanent fix, it will at least help me figure out where the problem is occurring. I actually tested this with my installed service and it works. I found out that unhandled exceptions actually do crash the service without writing anything to the log at all. I thought it'd at least report some application error, but it doesn't.
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//other code here
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Utilities.WriteIt(e.ExceptionObject as Exception);
}
It's always best to handle the exceptions. At least use a global exception handler and write it to a logfile
It sounds like your service is failing unexpectedly without doing any form of exception-handling and/or logging. Windows services do not automatically write exceptions to the Event Log - it's up to you to handle exceptions and (if they're fatal) write them out somewhere so that you can diagnose the problem.
At the very least, I'd recommend a logfile somewhere (perhaps in the service executable folder, or preferably somewhere else that's easy to get to and won't run afoul of permissioning issues) and a standard logging method that all your exception-handlers call to write their messages to.
If a service quits unexpectedly because of some exception, I am not sure it would end up in the Event Log automatically.
I would highly recommend a logging suite like log4net for more thorough logging. You'll be able to provide a multitude of logging 'levels' (debug traces to see if you reached some code, info traces for important events, error traces to log exceptions).
You can look here for an example of a EventLogAppender. However, I would suggest starting with getting a FileAppender, one of the easiest logs to create, working first and then add a second appender for the Event Log.
i did set start my windows service or NT service like everybody says a then
came up this message:
The service myService on local computer started an then stopped.Some services stop automatically if they are not in use by another services or programs
i've started other services and it never hapened...
before i change the value of a parameter that have to find it's value on a web service method
that look on a sql database...
and other change is that got formatted the hard disk...maybe i have to enable somethig
please i need help
It happens most likely because
you have an exception at startup... try to debug your things either by
using a log or by trying to reproduce your behavior in a windows app....
You can even debug your windows service using the following method...
Write the following code in your Service file...
public void OnDebug()
{
OnStart(null);
}
In the program file,
YourService myService = new YourService();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
This can happen when the logic performed using a windows service exceeds the default timeout.
We cannot overcome the default timeout of a windows service. Usually windows services are used to instantiate a method. So start a child thread within the OnStart event of the windows service and call your method within it.
If this is not solving your issue, put the code in try catch and log the exceptions. This error can happen if there is any exception within OnStart event too.
I'm writing a series of Windows services. I want them to fail if errors are thrown during startup (in OnStart() method). I had assumed that merely throwing an error in OnStart() would do this, but I'm finding that instead it "Starts" and presents me with a message stating "The service has started, but is inactive. Is this correct?" (Paraphrase). How do I handle the error so it actually fails to start the service?
If the main thing you want is for the Services window to report that there was an error, from what I've tried (.NET3.5 on Windows 7), the only way to do this is by setting the ExitCode. I recommend setting it to 13816, since this results in the message, "An unknown error has occurred." See the windows error codes.
The sample below accomplishes three things.
Setting ExitCode results in a useful message for the end-user. It doesn't affect the Windows Application log but does include a message in the System log.
Calling Stop results in a "Service successfully stopped" message in the Application log.
throwing the exception results in a useful log entry in the Application log.
protected override void OnStart(string[] args) {
try {
// Start your service
}catch (Exception ex) {
// Log exception
this.ExitCode = 13816;
this.Stop();
throw;
}
}
if you are running .NET 2.0 or higher, you can use ServiceBase.Stop to stop the service from OnStart. Otherwise call Stop from a new thread.
ref [devnewsgroups] (http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic50404.aspx)
(news group gone)
Move all of your startup logic to a separate method, and Throw exceptions (or call OnStop) from that seperate method.
OnStart has some oddities when starting up. I have found that if OnStart() has no more than one line in it, then I dont get the "The service started and then stopped.Some services stop automatically if they have no work to do" message, and thrown exceptions will terminate the process and log to the app event log.
Also with the seperate startup method, you can use a technique like this to debug it without attaching. http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx