Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Debug.Writeline stop working for some projects in the solution?

We have a solution with multiple projects after running the code from VS the output normally seen from Debug.Writeline statements just cease to appear. I mention the multiple projects because the output from one of the projects continues to appear. However, the other project consistently stops showing the output from the statements.

It's starting to drive me crazy. I should mention this is also occurring for a second developer on the project. Anyone seen this before, or have any ideas?

like image 681
Jay Avatar asked Sep 14 '26 22:09

Jay


2 Answers

After being tormented by this for years I finally found the cause and the solution in this Stack Overflow question: vs2010 Debug.WriteLine stops working

It seems that Visual Studio's handinlg of debug.writeline can't handle multiple processeses that each use multiple threads correctly. Eventually the 2 processes will deadlock the portion of visual studio that handles the output, causing it to stop working.

The solution is to wrap your calls to debug.writeline in a class that synchronizes across processes using a named mutex. This prevents multiple processes from writing to debug at the same time, nicely side stepping the whole deadlock problem.

The wrapper:

public class Debug
{
     #if DEBUG
         private static readonly Mutex DebugMutex =new Mutex(false,@"Global\DebugMutex");
     #endif

     [Conditional("DEBUG")]
     public static void WriteLine(string message)
     {
         DebugMutex.WaitOne();
         System.Diagnostics.Debug.WriteLine(message);
         DebugMutex.ReleaseMutex();
     }

     [Conditional("DEBUG")]
     public static void WriteLine(string message, string category)
     {
         DebugMutex.WaitOne();
         System.Diagnostics.Debug.WriteLine(message,category);
         DebugMutex.ReleaseMutex();
     }
}

Or for those using VB.NET:

Imports System.Threading

Public Class Debug
#If DEBUG Then
  Private Shared ReadOnly DebugMutex As New Mutex(False, "Global\DebugMutex")
#End If

<Conditional("DEBUG")> _
Public Shared Sub WriteLine(message As String)
    DebugMutex.WaitOne()
    System.Diagnostics.Debug.WriteLine(message)
    DebugMutex.ReleaseMutex()
End Sub

<Conditional("DEBUG")> _
Public Shared Sub WriteLine(message As String, category As String)
    DebugMutex.WaitOne()
    System.Diagnostics.Debug.WriteLine(message, category)
    DebugMutex.ReleaseMutex()
End Sub
End Class
like image 151
Bradley Uffner Avatar answered Sep 17 '26 21:09

Bradley Uffner


Follow these steps, it works for me

  1. Right click on your project
  2. Select Properties
  3. Select tab Build
  4. Make sure Define DEBUG constant is checked

Hope that helps

like image 36
onmyway133 Avatar answered Sep 17 '26 22:09

onmyway133



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!