Finding and Killing .NET Processes that you Disconnect from Instead of Stopping while Debugging on Windows

To see how to do this in Linux check this post.

When using Visual Studio Code to debug an application, I sometimes accidentally “Disconnect” the debug session instead of “Stopping” it. The same thing happens to me in Visual Studio and Rider. When I “Disconnect”, the process continues running, and I won’t be able to start another debug session until I kill the one that is running.

Method 1 - You know the process ID

In some cases when I try to debug again, the compilation will fail because the dlls can’t be overwritten. If this happens you might see the ID of the process that is locking those files.

Look in the compilation output for text indicating what process is holding those files, it will look something like this -

`The process cannot access the file 'bin\Debug\net7.0\SomeApp.dll' because it is being used by another process. The file is locked by: ".NET Host (17442)"

The process ID will be different for you.

To kill the process, open a command prompt as Administrator and run -

taskkill /PID 17442 /F

Now you should be able to debug your application.

Method 2 - You know the port number the application is using

The compilation doesn’t always fail due to locked files. If your application is holding onto a network port you will get an error like -

Failed to bind to address http://127.0.0.1:5038: address already in use.  

This one is easy to fix too. To find the process that is holding the port, open a command prompt as Administrator and run one of these -

netstat -ano | findstr 5038
# or
netstat -ano | grep 5038

You will see output like this -

TCP    127.0.0.1:5038         0.0.0.0:0              LISTENING       2488
TCP    127.0.0.1:5038         127.0.0.1:64485        ESTABLISHED     2488
TCP    127.0.0.1:64485        127.0.0.1:5038         ESTABLISHED     23588
TCP    [::1]:5038             [::]:0                 LISTENING       2488

Look in the second column for the port number (5038 in this case) and in the last column for the process ID (2488 in this case).

To kill the process run -

taskkill /PID 2488 /F

Method 3 - You know the name of the dll

This is probably the easiest method.

You can filter the list of running processes by the name of the dll.

Open a command prompt as Administrator and run -

tasklist /FI "MODULES eq SomeApp.dll"

You will get output like this -

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
dotnet.exe                   15808 Console                    1     88,848 K

To kill the process, look in the second column for the process ID (15808 in this case) and run -

taskkill /PID 15808 /F

Now you should be able to debug your application.

comments powered by Disqus

Related