Catching exception errors in a C# Windows service?

  • Thread starter Thread starter emdeusenet
  • Start date Start date
E

emdeusenet

Not sure if I have the correct group, but here goes.

I am trying to write a Windows service in c# and am having trouble
catching exceptions. I purposley tried to write to a bad file name
hoping that the exception would be caught and I could log to the event
log or external log file. For some reason when I use a try/catch block
nothing is "caught". I assume there is something else that is catching
exceptions and not passing to my catch block.

Any ideas?

Thanks.
 
That does not sound correct. It would be helpful to post a code sample that
demonstrates the problem.
 
I found out late last night that I was accidently stopping the service
in code just before the catch block, after I removed that everything
works fine :) Thanks for this link, I think it help me out a lot!
 
Sahil, now I have another question. If I wanted to add debug support by
referecing the "startup parameters" in the service control manager, for
some reason it does not work if I look for agrs in the Main procedure.
Anyone have ideas on how I could do this? My goal would be if a "debug"
parameter was specified in the control manager I would be able to log
certain events.

Here is what I have:

// in the class
public static bool debugMode = false;

....
static void Main(string[] args)
{

if ( args.Length > 0 )
{
if ( args[0].ToString() == "debug" )
{
debugMode = true;
}
}

I don't think it is ever getting to getting to "debugMode = true;"

Thanks again.
 
Looks like I answered my own question, placing the args routine in the
OnStart function instaed of Main fixed the problem.
 
Sahil said:
There is nothing special about a windows service, other than the fact
it is run by windows - not you (or the user).

While I agree with your statement about exception handling, I disagree
with this statement. For a start, the thread that runs the main service
function is not even the process's thread, it is created by the service
control manager (SCM) and is injected into the service.

Services are not started with CreateProcess, instead they are started by
the SCM. If the service does not complete it's initialization in a set
amount of time then the SCM will kill the service. There's also the
aspect of SCM control messages that are sent to the service, again,
totally different to how normal Win32 processes work.

Finally, services are designed to run under users other than the
interactive user (to be honest I cannot think of any reason why the
interactive user should run a service). This means that the service runs
in a Windows Station that is different to the one the interactive user
is using and so *everything* that has a GUI aspect will be invisible to
the interactive user, hence services should NEVER have a user interface.

So services are completely different to GUI or console processes.

Richard
 
Back
Top