2

我有一个Windows服务,我想收集有关使用Intellitrace的一些调试数据 - 问题是您无法通过直接从VS内部启动它来调试Windows服务。我已经安装了该服务,并且Service.Start中的第一条语句是“Debug.Break”,它允许我连接VS.但是,如果附加进程时已经启动,则无法使用Intellitrace。我可以使用VS2010的Intellitrace来收集Windows服务的数据吗?

有谁知道一种解决方法吗?

回答

4

这是可能的一点点的工作。总体思路是模拟将调用服务的OnStart和OnStop方法的控制台应用程序。这不是服务将要经历的确切的启动和停止路径,但希望它能让您知道您可以诊断您的问题。我包含了一些示例代码来给你一个大概的想法。

ConsoleMock.cs: 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using WindowsService1; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Service1 s1 = new Service1(); 
      while (true) 
      { 
       Console.WriteLine(">1 Start\n>2 Stop"); 
       string result = Console.ReadLine(); 
       if (result == "1") 
       { 
        var method = s1.GetType().GetMethod("OnStart", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); 
        method.Invoke(s1, new object[] { args }); 
       } 
       else if (result == "2") 
       { 
        var method = s1.GetType().GetMethod("OnStop", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); 
        method.Invoke(s1, new object[] { }); 
       } 
       else 
       { 
        Console.WriteLine("wrong command"); 
       } 
      } 
     } 
    } 
} 


Service.cs: 
    using System; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Diagnostics; 
    using System.Linq; 
    using System.ServiceProcess; 
    using System.Text; 
    using System.Threading; 

    namespace WindowsService1 
    { 
     public partial class Service1 : ServiceBase 
     { 
      private long serviceCounter; 
      private Thread workerThread; 

      public Service1() 
      { 
       InitializeComponent(); 
       serviceCounter = 0; 

      } 

      public void Worker() 
      { 
       while (true) 
       { 
        serviceCounter += 1; 
        System.Threading.Thread.Sleep(500); 

        try 
        { 
         throw new Exception(serviceCounter.ToString()); 
        } 
        catch (Exception) 
        { 
        } 
       } 
      } 

      protected override void OnStart(string[] args) 
      { 
       workerThread = new Thread(new ThreadStart(Worker)); 
       workerThread.Start(); 
      } 

      protected override void OnStop() 
      { 
       workerThread.Abort(); 
      } 
     } 
    } 
+0

这不能工作的任何少如飞!我已经用它创建了一个存根应用程序来测试我的Windows服务,而无需手动附加调试器 - 我的WinForm只有一个使用相同代码的启动和停止按钮,并且它完美地工作。如果可以的话,我已经给你三个upvotes了! – SqlRyan 2010-06-21 05:36:49

相关问题