How to determine if starting inside a windows service?

前端 未结 6 809
半阙折子戏
半阙折子戏 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:22

    It's not perfect, but you could probably do something like this:

    public static bool IsService()
    {
        ServiceController sc = new ServiceController("MyApplication");
        return sc.Status == ServiceControllerStatus.StartPending;
    }
    

    The idea is that if you run this while your service is still starting up then it will always be in the pending state. If the service isn't installed at all then the method will always return false. It will only fail in the very unlikely corner case that the service is starting and somebody is trying to start it as an application at the same time.

    I don't love this answer but I think it is probably the best you can do. Realistically it's not a very good idea to allow the same application to run in either service or application mode - in the long run it will be easier if you abstract all of the common functionality into a class library and just create a separate service app. But if for some reason you really really need to have your cake and eat it too, you could probably combine the IsService method above with Environment.UserInteractive to get the correct answer almost all of the time.

提交回复
热议问题