49

我目前正在为可以在控制台中运行的服务编写一些引导代码。它本质上归结为调用 OnStart() 方法,而不是使用 ServiceBase 来启动和停止服务(因为如果应用程序没有作为服务安装,它就不会运行应用程序,并使调试成为一场噩梦)。

现在我正在使用 Debugger.IsAttached 来确定是否应该使用 ServiceBase.Run 或 [service].OnStart,但我知道这不是最好的主意,因为有时最终用户希望在控制台中运行该服务(查看输出等实时)。

关于如何确定 Windows 服务控制器是否启动了“我”或用户是否在控制台中启动了“我”的任何想法?显然Environment.IsUserInteractive不是答案。我考虑过使用命令行参数,但这似乎很“脏”。

我总是可以看到有关 ServiceBase.Run 的 try-catch 语句,但这似乎很脏。编辑:尝试 catch 不起作用。

我有一个解决方案:把它放在这里给所有其他感兴趣的堆垛机:

    public void Run()
    {
        if (Debugger.IsAttached || Environment.GetCommandLineArgs().Contains<string>("-console"))
        {
            RunAllServices();
        }
        else
        {
            try
            {
                string temp = Console.Title;
                ServiceBase.Run((ServiceBase[])ComponentsToRun);
            }
            catch
            {
                RunAllServices();
            }
        }
    } // void Run

    private void RunAllServices()
    {
        foreach (ConsoleService component in ComponentsToRun)
        {
            component.Start();
        }
        WaitForCTRLC();
        foreach (ConsoleService component in ComponentsToRun)
        {
            component.Stop();
        }
    }

编辑: StackOverflow 上还有一个问题,该人在 Environment.CurrentDirectory 为“C:\Windows\System32”时遇到问题,看起来这可能是答案。我今天会测试。

4

13 回答 13

26

另一种解决方法.. 所以可以作为 WinForm 或 Windows 服务运行

var backend = new Backend();

if (Environment.UserInteractive)
{
     backend.OnStart();
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Fronend(backend));
     backend.OnStop();
}
else
{
     var ServicesToRun = new ServiceBase[] {backend};
     ServiceBase.Run(ServicesToRun);
}
于 2010-07-02T10:48:25.347 回答
20

我通常将我的 Windows 服务标记为控制台应用程序,它采用“-console”的命令行参数来使用控制台运行,否则它作为服务运行。要进行调试,您只需将项目选项中的命令行参数设置为“-console”即可!

这使得调试变得简单易用,并且意味着应用程序默认作为服务运行,这正是您想要的。

于 2008-10-14T06:28:55.437 回答
16

与 Ash 一样,我将所有实际处理代码编写在单独的类库程序集中,然后由 Windows 服务可执行文件以及控制台应用程序引用。

但是,有时了解类库是在服务可执行文件还是控制台应用程序的上下文中运行很有用。我这样做的方式是反映托管应用程序的基类。(对不起VB,但我想以下内容可以很容易地被c#化):

Public Class ExecutionContext
    ''' <summary>
    ''' Gets a value indicating whether the application is a windows service.
    ''' </summary>
    ''' <value>
    ''' <c>true</c> if this instance is service; otherwise, <c>false</c>.
    ''' </value>
    Public Shared ReadOnly Property IsService() As Boolean
        Get
            ' Determining whether or not the host application is a service is
            ' an expensive operation (it uses reflection), so we cache the
            ' result of the first call to this method so that we don't have to
            ' recalculate it every call.

            ' If we have not already determined whether or not the application
            ' is running as a service...
            If IsNothing(_isService) Then

                ' Get details of the host assembly.
                Dim entryAssembly As Reflection.Assembly = Reflection.Assembly.GetEntryAssembly

                ' Get the method that was called to enter the host assembly.
                Dim entryPoint As System.Reflection.MethodInfo = entryAssembly.EntryPoint

                ' If the base type of the host assembly inherits from the
                ' "ServiceBase" class, it must be a windows service. We store
                ' the result ready for the next caller of this method.
                _isService = (entryPoint.ReflectedType.BaseType.FullName = "System.ServiceProcess.ServiceBase")

            End If

            ' Return the cached result.
            Return CBool(_isService)
        End Get
    End Property

    Private Shared _isService As Nullable(Of Boolean) = Nothing
#End Region
End Class
于 2008-10-20T16:01:19.943 回答
15

什么对我有用:

  • 执行实际服务工作的类在单独的线程中运行。
  • 该线程从 OnStart() 方法内启动,并从 OnStop() 停止。
  • 服务模式和控制台模式之间的决定取决于Environment.UserInteractive

示例代码:

class MyService : ServiceBase
{
    private static void Main()
    {
        if (Environment.UserInteractive)
        {
            startWorkerThread();
            Console.WriteLine ("======  Press ENTER to stop threads  ======");
            Console.ReadLine();
            stopWorkerThread() ;
            Console.WriteLine ("======  Press ENTER to quit  ======");
            Console.ReadLine();
        }
        else
        {
            Run (this) ;
        }
    }

    protected override void OnStart(string[] args)
    {
        startWorkerThread();
    }

    protected override void OnStop()
    {
        stopWorkerThread() ;
    }
}
于 2008-10-16T10:47:17.283 回答
10

乔纳森,不完全是您问题的答案,但我刚刚完成了一个 Windows 服务的编写,并且还注意到调试和测试的困难。

通过简单地在单独的类库程序集中编写所有实际处理代码来解决它,然后由 Windows 服务可执行文件以及控制台应用程序和测试工具引用。

除了基本的计时器逻辑之外,所有更复杂的处理都发生在通用程序集中,并且可以非常容易地按需测试/运行。

于 2008-10-14T06:34:44.580 回答
10

我已修改 ProjectInstaller 以附加命令行参数参数 /service,当它作为服务安装时:

static class Program
{
    static void Main(string[] args)
    {
        if (Array.Exists(args, delegate(string arg) { return arg == "/install"; }))
        {
            System.Configuration.Install.TransactedInstaller ti = null;
            ti = new System.Configuration.Install.TransactedInstaller();
            ti.Installers.Add(new ProjectInstaller());
            ti.Context = new System.Configuration.Install.InstallContext("", null);
            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            ti.Context.Parameters["assemblypath"] = path;
            ti.Install(new System.Collections.Hashtable());
            return;
        }

        if (Array.Exists(args, delegate(string arg) { return arg == "/uninstall"; }))
        {
            System.Configuration.Install.TransactedInstaller ti = null;
            ti = new System.Configuration.Install.TransactedInstaller();
            ti.Installers.Add(new ProjectInstaller());
            ti.Context = new System.Configuration.Install.InstallContext("", null);
            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            ti.Context.Parameters["assemblypath"] = path;
            ti.Uninstall(null);
            return;
        }

        if (Array.Exists(args, delegate(string arg) { return arg == "/service"; }))
        {
            ServiceBase[] ServicesToRun;

            ServicesToRun = new ServiceBase[] { new MyService() };
            ServiceBase.Run(ServicesToRun);
        }
        else
        {
            Console.ReadKey();
        }
    }
}

然后修改 ProjectInstaller.cs 以覆盖 OnBeforeInstall() 和 OnBeforeUninstall()

[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
    public ProjectInstaller()
    {
        InitializeComponent();
    }

    protected virtual string AppendPathParameter(string path, string parameter)
    {
        if (path.Length > 0 && path[0] != '"')
        {
            path = "\"" + path + "\"";
        }
        path += " " + parameter;
        return path;
    }

    protected override void OnBeforeInstall(System.Collections.IDictionary savedState)
    {
        Context.Parameters["assemblypath"] = AppendPathParameter(Context.Parameters["assemblypath"], "/service");
        base.OnBeforeInstall(savedState);
    }

    protected override void OnBeforeUninstall(System.Collections.IDictionary savedState)
    {
        Context.Parameters["assemblypath"] = AppendPathParameter(Context.Parameters["assemblypath"], "/service");
        base.OnBeforeUninstall(savedState);
    }
}
于 2010-01-21T17:44:12.377 回答
4

这个线程真的很旧,但我想我会把我的解决方案扔在那里。很简单,为了处理这种情况,我构建了一个用于控制台和 Windows 服务案例的“服务工具”。如上,大部分逻辑都包含在一个单独的库中,但这更多是为了测试和“可链接性”。

随附的代码绝不代表解决此问题的“最佳”方法,只是我自己的方法。在这里,服务工具在“控制台模式”下由控制台应用程序调用,当它作为服务运行时由同一应用程序的“启动服务”逻辑调用。通过这样做,您现在可以调用

ServiceHost.Instance.RunningAsAService(布尔)

从代码中的任何位置检查应用程序是作为服务运行还是仅作为控制台运行。

这是代码:

public class ServiceHost
{
    private static Logger log = LogManager.GetLogger(typeof(ServiceHost).Name);

    private static ServiceHost mInstance = null;
    private static object mSyncRoot = new object();

    #region Singleton and Static Properties

    public static ServiceHost Instance
    {
        get
        {
            if (mInstance == null)
            {
                lock (mSyncRoot)
                {
                    if (mInstance == null)
                    {
                        mInstance = new ServiceHost();
                    }
                }
            }

            return (mInstance);
        }
    }

    public static Logger Log
    {
        get { return log; }
    }

    public static void Close()
    {
        lock (mSyncRoot)
        {
            if (mInstance.mEngine != null)
                mInstance.mEngine.Dispose();
        }
    }

    #endregion

    private ReconciliationEngine mEngine;
    private ServiceBase windowsServiceHost;
    private UnhandledExceptionEventHandler threadExceptionHanlder = new UnhandledExceptionEventHandler(ThreadExceptionHandler);

    public bool HostHealthy { get; private set; }
    public bool RunningAsService {get; private set;}

    private ServiceHost()
    {
        HostHealthy = false;
        RunningAsService = false;
        AppDomain.CurrentDomain.UnhandledException += threadExceptionHandler;

        try
        {
            mEngine = new ReconciliationEngine();
            HostHealthy = true;
        }
        catch (Exception ex)
        {
            log.FatalException("Could not initialize components.", ex);
        }
    }

    public void StartService()
    {
        if (!HostHealthy)
            throw new ApplicationException("Did not initialize components.");

        try
        {
            mEngine.Start();
        }
        catch (Exception ex)
        {
            log.FatalException("Could not start service components.", ex);
            HostHealthy = false;
        }
    }

    public void StartService(ServiceBase serviceHost)
    {
        if (!HostHealthy)
            throw new ApplicationException("Did not initialize components.");

        if (serviceHost == null)
            throw new ArgumentNullException("serviceHost");

        windowsServiceHost = serviceHost;
        RunningAsService = true;

        try
        {
            mEngine.Start();
        }
        catch (Exception ex)
        {
            log.FatalException("Could not start service components.", ex);
            HostHealthy = false;
        }
    }

    public void RestartService()
    {
        if (!HostHealthy)
            throw new ApplicationException("Did not initialize components.");         

        try
        {
            log.Info("Stopping service components...");
            mEngine.Stop();
            mEngine.Dispose();

            log.Info("Starting service components...");
            mEngine = new ReconciliationEngine();
            mEngine.Start();
        }
        catch (Exception ex)
        {
            log.FatalException("Could not restart components.", ex);
            HostHealthy = false;
        }
    }

    public void StopService()
    {
        try
        {
            if (mEngine != null)
                mEngine.Stop();
        }
        catch (Exception ex)
        {
            log.FatalException("Error stopping components.", ex);
            HostHealthy = false;
        }
        finally
        {
            if (windowsServiceHost != null)
                windowsServiceHost.Stop();

            if (RunningAsService)
            {
                AppDomain.CurrentDomain.UnhandledException -= threadExceptionHanlder;
            }
        }
    }

    private void HandleExceptionBasedOnExecution(object ex)
    {
        if (RunningAsService)
        {
            windowsServiceHost.Stop();
        }
        else
        {
            throw (Exception)ex;
        }
    }

    protected static void ThreadExceptionHandler(object sender, UnhandledExceptionEventArgs e)
    {
        log.FatalException("Unexpected error occurred. System is shutting down.", (Exception)e.ExceptionObject);
        ServiceHost.Instance.HandleExceptionBasedOnExecution((Exception)e.ExceptionObject);
    }
}

您在这里需要做的就是ReconcilationEngine用任何可以增强您的逻辑的方法替换那个看起来不祥的参考。然后在您的应用程序中,无论您是在控制台模式下运行还是作为服务运行,都使用ServiceHost.Instance.Start()and方法。ServiceHost.Instance.Stop()

于 2012-04-04T02:45:03.583 回答
3

也许检查进程父进程是否是 C:\Windows\system32\services.exe。

于 2008-11-04T07:31:17.520 回答
2

我发现实现这一点的唯一方法是首先检查控制台是否附加到进程,方法是访问 try/catch 块内的任何控制台对象属性(例如标题)。

如果服务是单片机启动的,没有控制台,访问属性会抛出System.IO.IOError。

但是,由于这感觉有点像依赖特定于实现的细节(如果某些平台上的 SCM 或某天决定为其启动的进程提供控制台怎么办?),我总是使用命令行开关(-console ) 在生产应用程序中...

于 2008-10-14T06:37:58.850 回答
1

这是 chksr 对 .NET 的回答的翻译,并避免了无法识别交互式服务的错误:

using System.Security.Principal;

var wi = WindowsIdentity.GetCurrent();
var wp = new WindowsPrincipal(wi);
var serviceSid = new SecurityIdentifier(WellKnownSidType.ServiceSid, null);
var localSystemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
var interactiveSid = new SecurityIdentifier(WellKnownSidType.InteractiveSid, null);
// maybe check LocalServiceSid, and NetworkServiceSid also

bool isServiceRunningAsUser = wp.IsInRole(serviceSid);
bool isSystem = wp.IsInRole(localSystemSid);
bool isInteractive = wp.IsInRole(interactiveSid);

bool isAnyService = isServiceRunningAsUser || isSystem || !isInteractive;
于 2015-01-14T02:54:50.163 回答
0

这有点像自插式,但我有一个小应用程序,它可以通过反射在你的应用程序中加载你的服务类型并以这种方式执行它们。我包含了源代码,因此您可以稍微更改它以显示标准输出。

使用此解决方案无需更改代码。我也有一个 Debugger.IsAttached 类型的解决方案,它足够通用,可以与任何服务一起使用。链接在这篇文章中: .NET Windows Service Runner

于 2008-10-14T06:39:11.017 回答
0

好吧,有一些非常古老的代码(大约 20 年左右,不是来自我,而是在狂野、狂野的网络中发现的,并且在 C 而不是 C# 中)应该让您了解如何完成这项工作:

enum enEnvironmentType
    {
    ENVTYPE_UNKNOWN,
    ENVTYPE_STANDARD,
    ENVTYPE_SERVICE_WITH_INTERACTION,
    ENVTYPE_SERVICE_WITHOUT_INTERACTION,
    ENVTYPE_IIS_ASP,
    };

enEnvironmentType GetEnvironmentType(void)
{
    HANDLE  hProcessToken   = NULL;
    DWORD   groupLength     = 300;
    PTOKEN_GROUPS groupInfo = NULL;

    SID_IDENTIFIER_AUTHORITY siaNt = SECURITY_NT_AUTHORITY;
    PSID    pInteractiveSid = NULL;
    PSID    pServiceSid = NULL;

    DWORD   dwRet = NO_ERROR;
    DWORD   ndx;

    BOOL    m_isInteractive = FALSE;
    BOOL    m_isService = FALSE;

    // open the token
    if (!::OpenProcessToken(::GetCurrentProcess(),TOKEN_QUERY,&hProcessToken))
        {
        dwRet = ::GetLastError();
        goto closedown;
        }

    // allocate a buffer of default size
    groupInfo = (PTOKEN_GROUPS)::LocalAlloc(0, groupLength);
    if (groupInfo == NULL)
        {
        dwRet = ::GetLastError();
        goto closedown;
        }

    // try to get the info
    if (!::GetTokenInformation(hProcessToken, TokenGroups,
        groupInfo, groupLength, &groupLength))
        {
        // if buffer was too small, allocate to proper size, otherwise error
        if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER)
            {
            dwRet = ::GetLastError();
            goto closedown;
            }

        ::LocalFree(groupInfo);

        groupInfo = (PTOKEN_GROUPS)::LocalAlloc(0, groupLength);
        if (groupInfo == NULL)
            {
            dwRet = ::GetLastError();
            goto closedown;
            }

        if (!GetTokenInformation(hProcessToken, TokenGroups,
            groupInfo, groupLength, &groupLength))
            {
            dwRet = ::GetLastError();
            goto closedown;
            }
        }

    //
    //  We now know the groups associated with this token.  We want
    //  to look to see if the interactive group is active in the
    //  token, and if so, we know that this is an interactive process.
    //
    //  We also look for the "service" SID, and if it's present,
    //  we know we're a service.
    //
    //  The service SID will be present iff the service is running in a
    //  user account (and was invoked by the service controller).
    //

    // create comparison sids
    if (!AllocateAndInitializeSid(&siaNt,
        1,
        SECURITY_INTERACTIVE_RID,
        0, 0, 0, 0, 0, 0, 0,
        &pInteractiveSid))
        {
        dwRet = ::GetLastError();
        goto closedown;
        }

    if (!AllocateAndInitializeSid(&siaNt,
        1,
        SECURITY_SERVICE_RID,
        0, 0, 0, 0, 0, 0, 0,
        &pServiceSid))
        {
        dwRet = ::GetLastError();
        goto closedown;
        }

    // try to match sids
    for (ndx = 0; ndx < groupInfo->GroupCount ; ndx += 1)
        {
        SID_AND_ATTRIBUTES  sanda = groupInfo->Groups[ndx];
        PSID                pSid = sanda.Sid;

        //
        //    Check to see if the group we're looking at is one of
        //    the two groups we're interested in.
        //

        if (::EqualSid(pSid, pInteractiveSid))
            {
            //
            //  This process has the Interactive SID in its
            //  token.  This means that the process is running as
            //  a console process
            //
            m_isInteractive = TRUE;
            m_isService = FALSE;
            break;
            }
        else if (::EqualSid(pSid, pServiceSid))
            {
            //
            //  This process has the Service SID in its
            //  token.  This means that the process is running as
            //  a service running in a user account ( not local system ).
            //
            m_isService = TRUE;
            m_isInteractive = FALSE;
            break;
            }
        }

    if ( !( m_isService || m_isInteractive ) )
        {
        //
        //  Neither Interactive or Service was present in the current
        //  users token, This implies that the process is running as
        //  a service, most likely running as LocalSystem.
        //
        m_isService = TRUE;
        }


closedown:
    if ( pServiceSid )
        ::FreeSid( pServiceSid );

    if ( pInteractiveSid )
        ::FreeSid( pInteractiveSid );

    if ( groupInfo )
        ::LocalFree( groupInfo );

    if ( hProcessToken )
        ::CloseHandle( hProcessToken );

    if (dwRet == NO_ERROR)
        {
        if (m_isService)
            return(m_isInteractive ? ENVTYPE_SERVICE_WITH_INTERACTION : ENVTYPE_SERVICE_WITHOUT_INTERACTION);
        return(ENVTYPE_STANDARD);
        }
      else
        return(ENVTYPE_UNKNOWN);
}
于 2014-09-12T11:43:37.000 回答
0

似乎我参加聚会有点晚了,但是作为服务运行时有趣的区别是,在启动时,当前文件夹指向系统目录(C:\windows\system32默认情况下)。在任何现实生活中,用户应用程序几乎不可能从系统文件夹开始。

所以,我使用以下技巧(c#):

protected static bool IsRunAsService()
{
    string CurDir = Directory.GetCurrentDirectory();
    if (CurDir.Equals(Environment.SystemDirectory, StringComparison.CurrentCultureIgnoreCase))
    { 
         return true; 
    }

    return (false);
}

对于未来的扩展,需要进行额外的检查System.Environment.UserInteractive == false(但我不知道它与“允许服务与桌面交互”服务设置有何关联)。

您还可以通过System.Diagnostics.Process.GetCurrentProcess().SessionId == 0(我不知道它与“允许服务与桌面交互”服务设置之间的关系如何)来检查窗口会话。

如果您编写可移植代码(例如,使用 .NetCore),您还可以检查Environment.OSVersion.Platform以确保您首先在 Windows 上。

于 2020-02-11T18:03:39.657 回答