Debug not stopping after form closing in Visual St

2019-04-07 00:34发布

问题:

Visual Studio Debug does not stop when i close the form that i write in C#. How can i stop debug process when i close form. I added Application.Exit() method in the form closing event but it didn't work.

Thank you.

回答1:

Try this from here

If (System.Windows.Forms.Application.MessageLoop)
{
  // Use this since we are a WinForms app
  System.Windows.Forms.Application.Exit()
}
Else
{
  // Use this since we are a console app
  System.Environment.Exit(1)
}

EDIT:

If there are running infinite threads then do

Thread myThread = new Thread(...);
myThread.IsBackground = true; //set your running thread to background
myThread.Start(...);

And you can see how to? from here



回答2:

Well this will be four years too late, however, I thought I'd post this for anyone else who runs into this issue (like I just did), sorry in advance if this is pretty basic, I'm fairly new to C# so this threw me for a bit.

I had the same issue as OP where, in my FormClosing event, neither Application.Exit() or Environment.Exit(0) would end the debugger.

The thing I found was looking at the reference count above my FormClosing event, it was showing '0 references'. I had just copied and pasted the closing event from another forum so there was no event handler to actually handle the event I had created/copied.

One easy way to resolve this (besides not copy and pasting code) was to create the event handler:

  • First go to the 'Form1.cs [Design]' tab
  • Navigate to the 'Properties' box
  • Click on 'Events'
  • Find 'FormClosing' and double click that

If you had the same issue you should now be able to see that there is at least 1 reference to the event. Now when you close the form it should also stop the debugger.



回答3:

Another possibility is, that your process runs in an exception which isn´t handled correctly. I used to show exception messages in self-build dialogs, but forgot to show the created window in one case. So the program ran into the exception, created the window but just didn´t show any sign of it... so the process kept running even when I closed the application.



回答4:

I landed on this question because VS was not stopping when a debugged application was shut down.

One way to see what might be causing the ide to hang is to click on pause and on the 'Debug Location' toolbar view any threads that are still running. For me I noticed that there was still a RabbitMq context that was not disposed of. So this was the clue i needed.

After I made the code change, VS now stops it debugging session once the application exits.

I know this is not a solution that you might be expecting but finding out why applications are not exiting properly or still keeping background processes alive is a very tricky subject. The active threads drop down is the best place to look imho.