c# - Stop service without error "Service cannot be started. The handle is invalid" -
i have windows service app , want stop service when main code executed. trying execute servicebase.stop() in onstart event, works fine, service stopped annoying error message in event viewer
"service cannot started. handle invalid"
any ideas how stop windows service without errors?
public partial class virtualserverinitservice : servicebase { public ilogger eventlogger = new eventlogger(); public virtualserverinitservice() { initializecomponent(); } protected override void onstart(string[] args) { eventlogger.write("starting service!"); new virtualserverinit(eventlogger).run(); eventlogger.write("virtualserverinit code executed"); stop();//this code works , gives error in event viewer } protected override void onstop() { eventlogger.write("stopping service!"); } }
use thread make sure onstart method finishes. threadpool put workitem on queue , once thread available execute run
method , calls stop
on service. windows service manager handled succesful start of service , hence no error sent eventlog when stop
called.
protected override void onstart(string[] args) { eventlogger.write("starting service!"); threadpool.queueuserworkitem( _ => { new virtualserverinit(eventlogger).run(); eventlogger.write("virtualserverinit code executed"); this.stop(); }; }
you might consider leaving service running , use customcommand control if actual work needs done. can override oncustomcommand
, send pre determined integer ask service perform particular task example calling sc virtualsvc control 128
commandline.
protected virtual void oncustomcommand(int command) { switch(command) { case 128: new virtualserverinit(eventlogger).run(); eventlogger.write("virtualserverinit code executed"); // maybe keep state if can run once break; default: eventlogger.write(string.format("unknown control code:{0}", command)); break; } }
Comments
Post a Comment