Debug.WriteLine()没有被命中

我正在使用以下代码调试Windows服务(通过在Visual Studio 2010中使用F5 ):

Program.cs文件中:

 static void Main() { if (!Environment.UserInteractive) { // We are not in debug mode, startup as service ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new MyServer() }; ServiceBase.Run(ServicesToRun); } else { // We are in debug mode, startup as application MyServer service = new MyServer(); service.StartService(); System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); } } 

MyServer.cs文件中:

 public void StartService() { this.OnStart(new string[0]); } 

在过去,我使用Debug.WriteLine("xxx")行在我的所有服务代码中没有任何问题,但现在我注意到不再调用所有Debug.WriteLine()行。

当我使用Step IntoF11 )进行调试时,我清楚地看到调试器跳过这些行 – (因此,输出窗口上没有输出文本),而服务在“调试模式”下正确启动。

我不明白为什么不调用Debug代码。 建议?

我在调试模式下构建我的解决方案(检查Define DEBUG constant ),但我注意到#if DEBUG ... #endif包围的代码未被调用。 这很奇怪……

似乎缺少Debug符号。

  1. 清理解决方案,重新启动Visual Studio,重建解决方案。
  2. 确保Configuration Manager处于调试模式。
  3. 检入工具>选项>调试并取消选中“启用我的代码”

发生在我身上,这似乎有所帮助。

如果您不使用调试版本,编译器将排除代码。 该方法的签名类似于:

 [Conditional("DEBUG")] public static void WriteLine(string message) { } 

当您进行调试构建时,该属性告诉编译器包含对相关方法的调用 。 因此,如果您没有使用DEBUG标志集(例如,发布版本)进行编译,则编译器将完全取消调用。

Debug.Assert也是如此。

您也可以在自己的代码中使用此属性,并使用您喜欢的任何标签。

另一种思考这个属性的方法是它强制对具有属性的方法的所有调用都包含在指令中 – 类似于:

  DoSomething(); #if DEBUG Debug.WriteLine("I'm a debug build"); #endif DoSomethingElse(); 

编辑

你想通过Environment.UserInteractive实现什么? 也许你的意思是Debugger.IsAttached ? 如果您想检查它是否是调试版本,那么您可以使用上面的ConditionalAttribute#if #endif指令。

Environment.UserInteractive与Debug模式不同 – 这只是意味着您在控制台而不是作为服务运行它。 确保您的构建配置设置为Debug。

导航到Project Properties – > Build并确保选中“Define DEBUG Constant”和“Define TRACE Con​​stant”复选框。

我有同样的随机问题。

我能够通过以下方式修复它:

  1. 取消选中 Project Properties -> Build -> Define DEBUG constant
  2. 单击保存
  3. 再次选中 'Define DEBUG constant'选项
  4. 单击保存
  5. 重建项目

执行此操作后,按预期命中#if DEBUG行。