35

What's the difference between

Debugger.Launch();
Debugger.Break();

?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nissim
  • 6,395
  • 5
  • 49
  • 74

4 Answers4

22

Reading the documentation, it sounds like Launch does nothing if the debugger is attached - it doesn't actually break (although I haven't verified this).

Break asks to launch the debugger (if not attached), and does do the break.

In reality, it is unlikely you'd have more than one Launch point... if that.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
21

Launch will start a debugger when one is available. But is just ignored if there is none available. Break will crash the program if no debugger is available.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    Especially the hint to the crash is helpful. I just found out that my release-version application crashed because of a forgotten debug.break. I thought the calls would only be executed in the debug version...I was wrong... – Sascha Jan 21 '16 at 05:13
11

More subtle differences:

  1. If a debugger is already attached, Debugger.Launch is a nop; whereas Debugger.Break will always break into the debugger.

  2. Launching a debugger does not actually break into the debugger. For example, in Visual Studio, Debugger.Launch will attach a debugger to the running process, but then you still need to do a Debug | Break in Visual Studio to actually break under the debugger.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike S
  • 3,058
  • 1
  • 22
  • 12
5

I'm not sure if anyone actually tried what's the difference or if it's different between .NET Framework and .NET 5 but this is the behavior when I test it:

result when running the example

After clicking OK VS will break on Debugger.Launch() (despite other answerers saying it will not):

enter image description here

However the debugger will not break on Debugger.Launch() if it is already attached.

If I pack my project as a dotnet Tool everything is the same except it doesn't know where to break:

enter image description here

TL;DR: In .NET 5:

With debugger attached:

  • .Launch() will do nothing
  • .Break() will break

Without debugger attached:

  • .Launch() will ask to attach a debugger and if you do, it will break at .Launch()
  • .Break() will do nothing (no exceptions)

Example.csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

</Project>

Program.cs:

using System;
using System.Diagnostics;

Console.WriteLine("Before break");

Debugger.Break();

Console.WriteLine("After break");

Console.WriteLine("Before Launch");

Debugger.Launch();

Console.WriteLine("After Launch");
Oskar
  • 1,996
  • 1
  • 22
  • 39