zoukankan      html  css  js  c++  java
  • An easier way to debug windows services

    Have you got tired of attaching the Visual Studio debugger to the service application? I got the solution just for you! It’s a small helper class containing a static method which you need to invoke.

    public static void Main(string[] argv)
    {
        // just include this check, "Service1" is the name of your service class.
        if (WindowsServiceHelper.RunAsConsoleIfRequested<Service1>())
            return;
    
        // all other code
    }

    Then go to project properties, the “Debug” tab and add “-console” as Command Arguments.

    Shows the debug settings under project properties

    How to configure Visual Studio

    That’s it. What I do is simply allocate a console using the winapi and then invoke (through reflection) the properprotected methods in your service class.

    Source code for the helper class:

    public static class WindowsServiceHelper
    {
        [DllImport("kernel32")]
        static extern bool AllocConsole();
    
        public static bool RunAsConsoleIfRequested<t>() where T : ServiceBase, new()
        {
            if (!Environment.CommandLine.Contains("-console"))
                return false;
    
            var args = Environment.GetCommandLineArgs().Where
    			(name => name != "-console").ToArray();
    
            AllocConsole();
    
            var service = new T();
            var onstart = service.GetType().GetMethod("OnStart", 
    		BindingFlags.Instance | BindingFlags.NonPublic);
            onstart.Invoke(service, new object[] {args});
    
            Console.WriteLine("Your service named '" + service.GetType().FullName + 
    			"' is up and running.
    Press 'ENTER' to stop it.");
            Console.ReadLine();
    
            var onstop = service.GetType().GetMethod("OnStop", 
    		BindingFlags.Instance | BindingFlags.NonPublic);
            onstop.Invoke(service, null);
            return true;
        }
    } 
  • 相关阅读:
    读完此文让你了解各个queue的原理
    借汇编之力窥探String背后的数据结构奥秘
    汇编高手带你玩转字符串,快上车!
    语雀调研
    产品技能一:抽象能力
    我所认知的敏捷开发
    产品经理需要的技能,我有吗?
    孙正义采访:接下来的30年,一切将被重新定义
    5G小白鼠
    goto语句为啥不受待见
  • 原文地址:https://www.cnblogs.com/yiwuya/p/3286282.html
Copyright © 2011-2022 走看看