0

I have a Topshelf C# service that must restore adapter DNS settings when exiting. My stop/start methods work just fine and this code works:

ManagementObject.InvokeMethod("SetDNSServerSearchOrder", DNS, null);

Shutdown, however, is a problem, even with RequestAdditionalTime

I log the following error:

2016-11-30 15:10:53,427 [7] TRACE MyDNSService - DNSService Shutdown command received.
2016-11-30 15:10:53,677 [7] DEBUG MyDNSService - DNSService Error setting DNS: A system shutdown is in progress. (Exception from HRESULT: 0x8007045B)

So it appears that the OS is blocking my call to ManagementObject.InvokeMethod

I'm stymied. Is there a way around this issue? On startup my service detects the anomaly and recovers, but that takes too long. I'd really like to be able to shutdown gracefully.

Rocky
  • 494
  • 6
  • 18
  • looks like you might find your answer here http://stackoverflow.com/questions/5217246/how-to-delay-shutdown-and-run-a-process-in-window-service – Gurpreet Dec 07 '16 at 22:13
  • Thanks, unfortunately that doesn't quite cover it. The service shutdown method executes fine, it's the OS that is blocking my call to set the DNS because of OS shutdown, not service shutdown. – Rocky Dec 08 '16 at 03:09
  • How about you set a marker that when OS comes back again and when your service starts, it should restore the DNS. cuz resetting DNS wont to anything anyway when machine is turned off. – Gurpreet Dec 09 '16 at 21:25
  • @Gurpreet That's my current work-around. – Rocky Dec 10 '16 at 20:42

1 Answers1

1

Rocky, I just re-created the functional elements of your code (logging what's happening) but I'm not getting the error. I'm setting the DNSServerSearchOrder to null and feeding that to the SetDNSServerSearchOrder method of the management object. https://github.com/paulsbruce/StackOverflowExamples/blob/master/PriorityShutdown/PriorityShutdown/MyService.cs

My only additional recommendation is that you can try changing the priority of the shutdown order of your service to see if that has any effect. See this thread: .NET Windows Services stopping order when the system shutdown

Community
  • 1
  • 1
Paul Bruce
  • 554
  • 2
  • 7
  • Whoa! Thanks so much. I don't quite understand what SetProcessShutdownParameters(0x3FF, 0x00000001); is doing, but I will try that. Bounty is going to be yours, I predict ... – Rocky Dec 13 '16 at 19:11
  • still getting my error but you've given me a good path to continue. Bounty is yours. I'll follow up again if I finally am able to figure out why my service is still erroring when setting DNS on shutdown. – Rocky Dec 13 '16 at 19:58