I have a windows service written in C# that creates multiple threads, and some threads have legacy code and I don't have enough time/access to legacy code to wait for all these threads to stop before OnStop() completes. Again at some point I dont have references to all threads as there are legacy codes. Now I want to update the service dynamically. So I start a different Updater service from my Job service. The Updater service will stop the Job service, download Job service exe and other dlls, replace these with old service exe, and dlls, and finally would restart the Job service. Upon start, Job service will stop the Updater service.
Now when the Updater service stops the Job service using ServiceController.Stop(), and also calls ServiceController.WaitForStatus(ServiceControllerStatus.Stopped), the Job service stops, but the some legacy threads spawned from Job service may not stop at that moment, and as a result the Job service exe cannot be updated.
I really dont find any good solution yet. The best solution could have been to use WaitHandles (AutoResetEvent/ManualResetEvent) to wait for all threads to finish, which is not happening. Or may be all threads could have been forcefully aborted which also seems critical. Another undesired solution could be to find all threads running in the service process and terminate/abort all threads which is not straightforward and also not a preferable solution at all. I was hopeful to use Environment.Exit in OnStop() but found that it causes Windows to show a bad alert message saying Process terminated unexpectedly (error 1067) which I have not been able to resolve at all.
Now I am confused what should be done at this moment in a short time without touching the legacy code. Any help would be appreciable.