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.
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.
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.
Related
I have a service which can automatically update itself. It does so by downloading and running the installer/updater, which is another executable. That executable stops the service with the ServiceController class, makes sure it is stopped using WaitForStatus(ServiceControllerStatus.Stopped), and then copies the relevant files. Those files include the service's main assembly and its dependencies.
Sometimes, the installation works as expected, but sometimes, I get an IOException telling me that it cannot access one of the service's assemblies because it is being used by another process (presumably the service which hasn't completely shut down). To remedy this I tried adding a fairly large delay of 1000ms after the WaitForStatus call, before starting to copy the files, but the IOException still gets thrown (or not) at random, i.e. sometimes the update is successful and sometimes it isn't.
I then tried adding a call to Environment.Exit() at the end of the ServiceBase.OnStop implementation of my service, and the update seems to work all the time now. However, I can tell this is not good practice since when I try stopping my service from the SCM, it stops, but gives the error Service process closed unexpectedly.
So what is the best way to do what I am trying to do? I could increase the delay, but it seems to me that 1000ms should be ample time for the service to properly shut down and release its lock on its assemblies. Perhaps I am doing something else incorrectly.
I'll write about what I did to solve this problem. I made it so that when a file isn't able to be copied because of that exception, the process enters a loop whereby it waits 1000ms and tries to copy that file again. It does so 5 times, and if it isn't able to copy the file after 5 times, the installer fails. In practice, from the log information I am receiving, it can take up to 3 seconds from a service process to properly shut down. I think this is the best solution for my problem.
I'm a bit of a beginner as far as programming is concerned. And looking at stack overflow I haven't found anything that quite answers my question.
I have created a C# console application that is used to push an XML file to a web service that I don't control. It does this by creating an http webrequest. The service will probably be running on windows server 2008, or a win 7 varient. Development is done in VS 2010.
My end goal is to run this program twice a day with little user involement. And I was told that services were the best way to do this. I know that services do not take user input and that outputs are usually to a log file. My console app dosn't take user input but must have the ability to C.R.U.D. files. Beacuse it creates and then reads an XMl file into the web request. If needed I should have no problems having it write any errors to a log file, but at current though it creates/sends an error report via email.
I have 2 questions:
Question 1:
I would like this service to call the application every 12 hours, Is it more reliable/better practice to use a service to determine when to run the application? Or use windows' built in scheduler, or a .net solution like quark? I'm looking for reliability and also, little user involvement. Kind of a set and forget deal.
Question 2:
What would the suggested best practice be for converting my program?
INFO: I have previously created a empty windows service that I would like to fold my application into. (This was done via tutorial, the service contains all that is needed to for a service but it dosn't do anything... yet! OnStart, OnStop, installer etc.) What would be the best way to do it? Should I call my application inside the service's OnStart() method? Our should I add the application as a dll to the service. It's not that I don't think I could do it. It's just my searches on the matter seem to point out that it would be better to just start from a service and add some code to that. My goal would be to minimise the code needed to convert this application.
Thanks for all your help,
Chris
I like standalone programs run by the scheduler because they are easier to write and test.
Services would be more appropriate when they have to be running all the time...say to monitor something.
Question 1: Personally running twice a day seems like a scheduled task type of operation
Question 2: I'd describe it as: more or less put the body of static void Main(string[] args) into the OnStart method. Then also create a timer in OnStart which will call the trigger function in your class. But then I've only stumbled my way through writing windows services so I'm not 100% certain on this advice...
One consideration might be whats the risk of anything failing in the process? If there is a chance of an unhandled exception, the service will die and either would need special settings to restart it or complete error handling to be coded. Where a scheduled task will always automatically retry at the next trigger interval.
I have a process that I need to make into a service. This process runs autonomously right now so there are no concerns with user interaction I just need to "turn" it into a service. I got to thinking about it and decided that I could just create a service that launched the process, this would give me the added benefit of having outside control of the process.. I could watch it for an unexpected exit and re-launch it.. I could also watch its memory usage and kill it if it gets out of hand. I dont think I have seen many other applications do this and I was thinking there must be a reason why so...
It's going to add complexity.
Instead of just having the process exist, you'll now need to make a second executable to "launch and monitor" this process. This adds overhead (the service and process both running), adds complexity, and makes life as a whole a bit more difficult.
That being said, if you've got a .NET Console application, turning it into a service is incredibly trivial. Your Main routine basically just gets moved into a method, and launched in a thread. Once you do that, the service application is effectively done - it's just configuring the service (which can be done in a designer) and overriding OnStart to spin up a thread and call your routine.
This is a good idea, but you've reinvented the wheel. What you're thinking of is essentially server monitoring. There are several high-quality open source implementations of what you want.
Pretty much anything that you can do this way you can do with less complexity by just putting the application logic in the service. Not to mention that you get Service Recovery for free by doing it in the service directly.
My c# windows service is dying due to an unknown error deep down in one of the worker threads that it creates.
Is there any way to find out the exception that causes the service to be terminated?
(Without writing in a dozen try / catch / log the error codes).
Just a simple one-time report on the error that caused the service to shut down.
It is simple, implement an event handler for AppDomain.CurrentDomain.UnhandledException and log the value of e.ExceptionObject.ToString().
I'd say that it might be useful to add the dozen try catch so that the next time something goes wrong, you'll have a log of the error (especially useful if you later find an issue that only occurs sometimes in unclear circumstances so difficult to reproduce while debugging).
However, other than that, you can attach Visual Studio to a running process as shown in this MSDN article. To avoid having to do that I usually add some code to the startup of the service so that if the exe is started with a -c command line parameter, it'll run as a normal process which can be started from Visual Studio. This Code Project article shows something similar to this.
There's a couple of things that you can do. First, check the Windows error logs if you haven't already - I know this is probably obvious, and they can be a bit light on information, but it's always worth a look, because occasionally it will help.
The second approach is just a little bit more involved, and I know you've asked for something really quick and one-time, but to be honest I'm about to recommend the best way to develop Windows services, and once you've done it, you will never go back... and it will save you hours of pain, so I'll give you the advice anyway:
Extract the core of your service to be run independently in a simple console app host. This approach means that you can fully run and debug it in Visual Studio running as a plain old executable, or even on your test server with a remote debugging session attached. For the real "live" windows service, your service code is a thin wrapper around your testable, debuggable service core. This has worked for me time and time again.
Your core service will expose Start() and Stop() methods that can be called by your Windows Service host in production. That's it.
There's a really good OSS project called Topshelf that provides a full-featured and well-tested version of the wrapper I've described and you can read a developer's example of it in use it here.
The easy way is transferring the errors from VS to windows error log and checking there. You have to use some third party tools if you prefer to get error log list as a report instead.
Logger in c#
if you prefer go for a simpler/cheaper one try the above code. Its is very easy and simpler than u thought
I hate asking questions like this - they're so undefined... and undefinable, but here goes.
Background:
I've got a DLL that is the guts of an application that is a timed process. My timer receives a configuration for the interval at which it runs and a delegate that should be run when the interval elapses. I've got another DLL that contains the process that I inject.
I created two applications, one Windows Service and one Console Application. Each of the applications read their own configuration file and load the same libraries pushing the configured timer interval and delegate into my timed process class.
Problem:
Yesterday and for the last n weeks, everything was working fine in our production environment using the Windows Service. Today, the Windows Service will run for a period of around 20-30 minutes and hangs (with a timer interval of 30 secods), but the console application runs without issue and has for the past 4 hours. Detailed logging doesn't indicate any failure. It's as if the Windows Service just...dies quietly - without stopping.
Given that my Windows Service and Console Applications are doing the exact same thing, I can only think that there is something that is causing the Windows Service process to hang - but I have no idea what could be causing that. I've checked the configuration files, and they're both identical - I even copied and pasted the contents of one into the other just to be sure. No dice.
Can anyone make suggestions as to what might cause a Windows Service to hang, when a counterpart Console Application using the same base libraries doesn't; or can anyone point me in the direction of tools that would allow me to diagnose what could be causing this issue?
Thanks for everyone's help - still digging.
You need to figure out what changed on the production server. At first, the IT guys responsible will swear that nothing changed but you have to be persistent. i've seen this happen to often i've lost count. Software doesn't spoil. Period. The change must have been to the environment.
Difference in execution: You have two apps running the same code. The most likely difference (and culprit) is that the service is running with a different set of security credentials than your console app and might fall victim to security vagaries. Check on that first. Which Windows account is running the service? What is its role and scope? Is there any 3rd party security software running on the server and perhaps Killing errant apps? Do you have to register your service with a 3rd party security service? Is your .Net assembly properly signed? Are your .Net assemblies properly registered and configured on the server? Last but not least, don't forget that a debugger user, which you most likely are, gets away with a lot more stuff than many other account types.
Another thought: Since timing seems to be part of the issues, check the scheduled tasks on the machine. Perhaps there's a process that is set to go off every 30 minutes that is interfering with your own.
You can debug a Windows service by running it interactively within Visual Studio. This may help you to isolate the problem by setting (perhaps conditional) breakpoints.
Alternatively, you can use the Visual Studio "Attach to process" dialog window to find the service process and attach to it with the "Debug CLR" option enabled. Again this allows you to set breakpoints as needed.
Are you using any assertions? If an assertion fires without being re-directed to write to a log file, your service will hang. If the code throws an unhandled exception, perhaps because of a memory leak, then your service process will crash. If you set the Service Control Manager (SCM) to restart your process in the event of a crash, you should be able to see that the service has been restarted. As you have identical code running in both environments, these two situations don't seem likely. But remember that your service is being hosted by the SCM, which means a very different environment to the one in which your console app is running.
I often use a "heartbeat", where each active thread in the service sends a regular (say every 30 seconds) message to a local MSMQ. This enables manual or automated monitoring, and should give you some clues when these heartbeat messages stop arriving.
Annother possibility is some sort of permissions problem, because the service is probably running with a different local/domain user to the console.
After the hang, can you use the SCM to stop the service? If you can't, then there is probably some sort of thread deadlock problem. After the service appears to hang, you can go to a command-line and type sc queryex servicename. This should give you the current STATE of the service.
I would probably put in some file logging just to see how far the program is getting. It may give you a better idea of what is looping/hanging/deadlocked/crashing.
You can try these techniques
Logging start logging the flow of the code in the service. Have this parameter based so you dont have a deluge after you are done. You should log all function names, parameters, timestamps.
Attach Debugger Locally or Remotely attach a debugger with the code to the running service, set appropriate breakpoints (can be based on the data gathered from logging)
PerfMon Run this utility and gather information about the machine that the service is running on for any additional clues (high CPU spikes, IO spikes, excessive paging, etc)
Microsoft provides a good resource on debugging a Windows Service. That essentially sounds like what you'd have to do given that your question is so generic. With that said, has any changes been made to the system over the last few days that could aversely affect the service? Have you made any updates to the code that change the way the service might possibly work?
Again, I think you're going to have to do some serious debugging to find your problem.
What type of timer are you using in the windows service? I've seen numberous people on SO have problems with timers and windows services. Here is a good tutorial just to make sure you are setting it up correctly and using the right type of timer. Hope that helps.
Another potential problem in reference to psasik's answer is if your application is relying on something only available when being run in User Mode.
Running in service mode runs in (is it desktop0?) which can cause some issues in my experience if you are trying to determine states of something that can only be seen in user mode.
Smells like a threading issue to me. Is there any threading or async work being done at all? One crucial question is "does the service hang on the same line of code or same method every time?" Use your logging to find out the last thing that happens before a hang, and if so, post the problem code.
One other tool you may consider is a good profiler. If it is .NET code, I believe RedGate ANTS can monitor it and give you a good picture of any threadlock scenarios.