如何判断Visual Studio托管过程中是否运行了代码

时间:2013-12-09 17:52:03

标签: visual-studio

有没有办法确定代码是否在Visual Studio托管过程中运行?我有一个正在运行的服务,我将通过VS运行它,具有所有“逐步”功能或正常运行(即启动Windows服务)。

1 个答案:

答案 0 :(得分:0)

我找到了似乎有效的解决方案

    public static void Main()
    {
        // If running as part of the Visual Studio hosting process then use
        // reflection to invoke the service via reflection (otherwise it does
        // not allow direct starting of a service).  If not in interactive mode
        // then just start and run the service
        if (System.Environment.UserInteractive)
        {
            var service = new HostService();
            MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
            onStartMethod.Invoke(service, new object[] { new string[] { } });

            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
        }
        else
        {
            ServiceBase[] services = new ServiceBase[] 
                { 
                    new HostService()
                };
            ServiceBase.Run(services);
        }
    }