Paul DeVito
Paul DeVito

Reputation: 1912

How to Debug a .NET Core Console App When Using dotnet run

So I'm working on a custom dotnet cli tool as described here. I'm getting started with it and can run my console app using dotnet run, but it's going right past my breakpoints when trying to debug. It does work when running from VS, but I want to be able to play around with passing various arguments and doing that from the application arguments box is not really practical. Any thoughts?

Upvotes: 14

Views: 38012

Answers (3)

DmitryKosarev
DmitryKosarev

Reputation: 11

There is the implementation of the debugger call in the MsBuild repo, DebuggerLaunchCheck function.
It is more convenient to attach to "right" process.
Stop occurs if a certain environment variable is set.
src/MSBuild/XMake.cs#L603

   Process currentProcess = Process.GetCurrentProcess();
   Console.WriteLine($"Waiting for debugger to attach 
   ({currentProcess.MainModule.FileName} PID {currentProcess.Id}).  Press 
   enter to continue...");
   Console.ReadLine();
   break;

Launch:

  Set CONSOLEDEBUGONSTART="2"
  dotnet run

Upvotes: 0

Paul DeVito
Paul DeVito

Reputation: 1912

For what it's worth, it seems like the best way is unfortunately to pass them in as arguments.

You can do this by clicking on the arrow next to Run button in Visual Studio and selecting 'Project Debug Properties'. From there, you can go to 'Application Arguments' and enter the arguments you want. For example, something like --list all would pass in an array with a length of two where index 0 is --list and index 1 is all.

If someone comes up with a less invasive way, let me know!

Edit: You can also do it from command prompt/powershell by using dotnet run and attaching to the associated process in VS (Debug>Attach to Process)

Upvotes: 3

Link
Link

Reputation: 1711

You have multiple options:

  1. Debugger.Launch This is a function which will pop up a window where you can attach a Visual Studio Debugger. See: Debugger.Launch. This has one theoretical downside (which does not apply to you) it is only usable in Visual Studio and not for example in Rider as the API is not open. (But you when this window pops up you could attach Rider to the process)

  2. "Wait" the first seconds in your program You could just pass an argument to your cli which indicates it should wait x seconds so that you can attach your Debugger.

public static void Main(string[] args)
{
    if(args[0] == "waitfordebugger")
    {
        Thread.Sleep(10000); // Wait 10 Seconds
    }

    // Do stuff here

You then call your program like this: dotnet run -- waitfordebugger

Upvotes: 6

Related Questions