How to determine if starting inside a windows service?

前端 未结 6 784
半阙折子戏
半阙折子戏 2021-02-15 16:37

Currently I\'m checking it in the following way:

if (Environment.UserInteractive)
    Application.Run(new ServiceControllerForm(service));
else
    ServiceBase.R         


        
6条回答
  •  借酒劲吻你
    2021-02-15 17:35

    The issue with the accepted answer is that checking the status of an service that isn't installed will throw. The IsService Method I'm using looks like this:

        private bool IsService(string name)
        {
            if (!Environment.UserInteractive) return true;
            System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(name);
            try
            {
                return sc.Status == System.ServiceProcess.ServiceControllerStatus.StartPending;
            }
            catch(InvalidOperationException)
            {
                return false;
            }
        }
    

    Which should work more reliably than just checking Environment.UserInteractive

提交回复
热议问题