【问题标题】:Tools to test newly created Windows Services?测试新创建的 Windows 服务的工具?
【发布时间】:2011-05-15 17:10:59
【问题描述】:

是否有测试我的 Windows 服务的工具或方法? 它可以在 Visual Studio 2010 中正常编译。

我使用 Advanced Installed 创建安装包 (MSI) 但无法启动!

干杯

【问题讨论】:

  • 您有任何错误吗?如果有,是什么样的?
  • @Rhapsody 我使用 Advanced installed 安装服务但无法启动!
  • 您能在 Windows 事件日志中找到任何错误吗?

标签: c# visual-studio-2010 testing windows-services


【解决方案1】:

请参阅 lubos hasko 的 this answer 以简化调试并简化服务安装(我已经取得了巨大的成功)。还建议调整 log4net 并让它以交互模式登录到控制台。

class TheService : ServiceBase
{
   static void Main(string[] args)
        {
            if (!Environment.UserInteractive)
            {
                Run(new TheService());
            }
            else
            {
                // If interactive, start up as a console app for easy debugging and/or installing/uninstalling the service
                switch (string.Concat(args))
                {
                    case "/i":
                        ManagedInstallerClass.InstallHelper(new[] { Assembly.GetExecutingAssembly().Location });
                        break;
                    case "/u":
                        ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location });
                        break;
                    default:
                        Console.WriteLine("Running service in console debug mode (use /i or /u to install or uninstall the service)");
                        var service = new TheService();
                        service.OnStart(null);
                        Thread.Sleep(Timeout.Infinite);
                        break;
                }
            }
        }
   }

【讨论】:

    【解决方案2】:

    您的应用程序中是否有任何日志记录?这可能是第一个检查解决方法的地方。拥有“工具”来测试“某些 Windows 服务”是相当困难的。如果您从日志记录中获得了更多详细信息并且您无法找出问题所在,请告知它,以便我们能够提供帮助。

    【讨论】:

      【解决方案3】:

      您不能直接运行 Windows 服务:您必须安装该服务并启动它。

      由于在开发时安装服务往往不方便,因此值得修改服务的引导代码,以检测它是作为服务运行还是以交互方式运行,在后一种情况下,显示 Windows 窗体。

      ServiceBase service = ...;
      
      if (Environment.UserInteractive)
      {
          // run as application
          Application.EnableVisualStyles();
          Application.Run(new SomeForm()); // the form should call OnStart on the service
      }
      else
      {
          // run as service
          ServiceBase.Run(service);
      }
      

      【讨论】:

        【解决方案4】:

        我假设您正在使用安装程序类来创建和安装服务(派生自 System.Configuration.Install.Installer)?如果是这样,请将这行代码放在安装程序的 ctr 中或 OnBeforeInstall 覆盖。然后您可以附加一个调试器,并调试安装过程:

        System.Diagnostics.Debugger.Break()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-28
          • 1970-01-01
          • 1970-01-01
          • 2011-02-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多