如何确定是否在Windows服务内部启动

如何确定是否在Windows服务内部启动

本文介绍了如何确定是否在Windows服务内部启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

目前我正在通过以下方式进行检查:

Currently I'm checking it in the following way:

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

它有助于调试,也可以使用可执行文件运行服务.但是现在假设该服务需要与用户桌面交互,因此我必须在属性中启用允许服务与桌面交互".这当然打破了这种检查方式.还有别的方法吗?

It helps debugging a little and service can also be run using the executable. But assume now that the service requires interaction with the user desktop so that I have to enable "Allow service to interact with desktop" in the properties. This of course breaks this way of checking. Is there another way?

推荐答案

它并不完美,但你可以这样做:

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;
}

这个想法是,如果您在服务仍在启动时运行它,那么它将始终处于挂起状态.如果根本没有安装该服务,则该方法将始终返回 false.它只会在极不可能的极端情况下失败,即服务正在启动并且有人试图同时将其作为应用程序启动.

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.

我不喜欢这个答案,但我认为这可能是你能做的最好的.实际上允许相同的应用程序在服务或应用程序模式下运行并不是一个好主意 - 从长远来看,如果您将所有通用功能抽象到一个类库中并且只是创建一个单独的服务应用程序.但是如果由于某种原因你真的真的需要你的蛋糕并吃掉它,你可以将上面的 IsService 方法与 Environment.UserInteractive 结合起来>几乎每次都能得到正确答案.

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.

这篇关于如何确定是否在Windows服务内部启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 11:13