Detect if code is running as a service

前端 未结 9 1371
谎友^
谎友^ 2020-12-10 16:30

Is there a way for an .NET library to detect whether or not it is being run as a service?

My library can be run either way. But when its run as a service, developer

相关标签:
9条回答
  • 2020-12-10 16:46

    The answer by 0xA3 to this question actually contains C# code to query the SCM, much like Rob Parker describes in his answer.

    0 讨论(0)
  • You can add the Microsoft.Extensions.Hosting.WindowsServices NuGet package and use the WindowsServiceHelpers.IsWindowsService() helper method.

    For Linux you can use Microsoft.Extensions.Hosting.Systemd and the SystemdHelpers.IsSystemdService() method.

    0 讨论(0)
  • 2020-12-10 16:53

    You should probably check that you are running in session zero (at least if you are targeting Vista). You can use WTSRegisterSessionNotification, like in this sample:

      [DllImport("kernel32.dll")]
      private static extern int WTSGetActiveConsoleSessionId();
    
    0 讨论(0)
提交回复
热议问题