IDisposable code at process termination

I have an old old Windows service (inheriting from System.ServiceProcess.ServiceBase) to which I added a component (implementation of IComponent) to this.components.Add(new MyStuff());
However, MyStuff Disposable() does not start if I disable exe from task manager.

Possible suspects:

  • Nothing starts in the "End Process". If so, how can I clean up after myself (for example, did the processes start to kill?)
  • For testing purposes, I start my service with

    var service = new MyService();
    service.Run();
    Thread.Wait(Timeout.Infinite);

    instead of ServiceBase.Run(new []{new MyService()}); might be a problem?

  • ServiceBase is not cleared automatically. If so, what should I do?

Please, help!

Additional info: I'm trying to close other exes that I started with my service using Process.Start (...), so if there is a way to make them autocomplete (a child process?), Which is also good.

+4
source share
3 answers

My typical way to have children detect the death of a parent:

  • Create a nice long random name during parent run
  • In addition, during startup, get a named mutex with that name and save the parent locked for life.
  • When starting a child process, pass a long random name as a parameter
  • In children, a thread is allocated that tries to get the same named mutex.
  • If a child ever gets a mutex, the parent process had to die - so the child should go out and

By using a random name for the mutex, you guarantee that a new hierarchy can be built even when the parent / child hierarchy is in the process of being closed.

+2
source

Why are you stopping the service using the task manager, you are basically killing it, and not asking it to do something.

Put some code in the OnStop method to clear and use the Service Manager to stop / start the service.

+2
source

If you β€œpull out the plug,” you cannot do anything at that moment. This is not considered a controlled outage. This is completely unexpected, and nothing will give you the strength to deal with it from within the process that is killed. This is not even considered a stop. To make it clear: you are not closing, you are killing him! It is like removing the power cord from your computer and waiting for its grace. Don't work (although I had a tester that wrote me a very accurate test several years ago ...)

Solve it:

  • Your child processes will need to ping the parent process. If he does not answer, you know that something is wrong and turns off gracefully.

  • Or refer to ChrisBint (Service Controller) answer. Get a service by name, start and stop it.

Find sample code here: http://www.csharp-examples.net/restart-windows-service/

+2
source

All Articles