Visual Studio is keeping a handle open after stopping the debugger - c#

I keep getting the following error in MS Visual Stdio:
Unable to copy file "obj\Debug[Program].exe" to "bin\Debug[Program].exe". The process cannot access the file 'bin\Debug[Program].exe' because it is being used by another process.
This happens randomly after I close and/or stop the debugger. The program is closed, but VS keeps a couple handles open to the program.
The only way I've found to be able to re-debug is to close Visual Studio, and reopen it, which is very annoying.
Any idea why this is happening, and how I can run the debugger again without first closing it?
This has happened in 2013 Ultimate, and 2015 Ultimate.
Thanks.

I am going to propose a new solution, that permanently fixes it. I have always done this, when experiencing "Debugger" issues that occur mostly when moving to a new Visual Studio with an old Solution, so your mileage may vary.
If, switching back to AnyCPU configuration allows you to debug again, then I believe the following steps will fix it.
Go into "Configuration Manager", change "Active solution platform:" to Any CPU, click the down Arrow again, and select "Edit...", delete ANY custom entries here, even if it is just x86 and x64.
In the same Window, enter the Platform under your Project and repeat Step 1. Remove all entries but AnyCPU.
Close Configuration Manager.
Go to "Build" menu and click "Clean Solution".
Restart Visual Studio 2015 CTP 5 as Administrator. Open your solution. Use "Any CPU" for one build, Release or Debug, and then close back out of it. Just verify you are able to basically use the "Any CPU" target still.
Minimize Visual Studio, go into your solution and clean out all your Bins/Release and Debugs, including any x86/x64 Release/Debug folders if they are still present.
Maximize Visual Studio, enter Configuration Manager, rebuild your platform targets (x86/x64) copying settings from the verified working: "Any CPU".
Start happily working again!
The error is caused by incorrect, out of date, or corrupted "Target Platform" settings saved in the Solution / Project. You can repeat the steps above, again removing the "Any CPU" setting under the Project Solutions, as it can also have bad juju cached in there. Adding it again with the terms "Any CPU" settings copy settings "Empty Settings" may also fix the issue. You then want to remove everything else, and re-add it as x86/x64 using the new Any CPU settings.
Decided to make a How-To with illustrations on my blog/site.
Now if you only have "Any CPU" as your configuration as an issue, there are three things that can cause this. "Any CPU" setting that needs refreshing, open stream can equal open handles, or possibly a StackOverflow exception, just hasn't overflowed yet.
If this is occurring with "Any CPU" and you have no other target solutions, you may first want try this. Add one new platform target, x86/x64, Copy settings from Any CPU is fine. This will allow you to remove Any CPU, from the Configuration Manager and the Solution. You can then Add a new solution, called Any CPU, with "empty settings" as the setting option. Then remove x86/x64. This forces a refresh of the Any CPU configuration inside your project. Try having a build or two.
If it is still occurring, you more than likely need to revisit your code if it is occurring with "Any CPU". This could be a bad streaming/unclosed stream issue, a poor COM call that is hung in system etc. Whenever I am experimenting with Unmanaged code, or system processes, I try and handle application hangs and StackOverflows. Which may be occurring as mentioned previously.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException +=
new ThreadExceptionEventHandler(Application_ThreadException);
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("Congratulations, you have broken this program like no other user before you!\n\n" +
"Exception : " + ex.Message + "\n\n" + "Stack : " + ex.StackTrace,
"Ridonculous Exception Occurred", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
try
{
MessageBox.Show("This is a StackOverflow Exception!\n\n" +
"Exception : " + e.Exception.Message + "\n\n" + "Stack : " + e.Exception.StackTrace,
"Ridonculous StackOverflow Exception Occurred", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
Source: http://tech.pro/tutorial/668/csharp-tutorial-dealing-with-unhandled-exceptions
Alternatively: If you have multi-Visual Studio installs, or even preview Vstudios installed, you may break JIT unknowingly by switching back and forth or running Updates. The latest version(s) of Visual Studio actually informs you of JIT errors (potential or not) and advises you to repair the IDE.
Anything else, would be beyond my level of knowledge. Best of luck to you!

RagingCain has some excellent solutions. If all else fails, the following will:
Use Process Explorer to close the handles to the file.
Manually Delete the .exe file
After that, it should recompile.

Project properties - Disable the Visual Studio Hosting process.
Worked for me.

Related

Debugger operation failed The request is not supported. (Exception from HRESULT: 0x80070032)

I have a C# project that was initially created by VS2013. I open it in Xamarin and it builds fine, the executable file is created and can be started from outside Xamarin.
But if I try to start it with Run->Start Debugging, it shows this error:
Debugger operation failed
The request is not supported. (Exception from HRESULT: 0x80070032)
The only similar question I found was for F# - Debugging F# in Xamarin Studio 4.0.3 throws an error, and they suggest it is because the project is 64-bit, but I'm not sure if this applies to C# as well.
How can I fix this error?
If you arrive here as a result of trying to debug a unit test in Xamarin (in my case on a Mac) and you see the Debugger Operation Failed message, it may be because in the drop-down for your chosen build (on the header bar area) you still have release selected. I switched that to debug, and then the option in the unit tests to 'debug test' worked.
It really did turn out to be because of the architecture. But in my case the architecture was AnyCPU, not x64, and it couldn't be changed from inside Xamarin:
So instead I opened the .csproj file in Notepad++ and used Replace All to replace all mentions of "AnyCPU" to "x86". After reloading the solution in Xamarin, the debugger now works.
I got this same error while adding a binding in IIS Manager. It also prevented Windows Update to check updates. The issue was the cipher suite list.
If you come across the same issue, here is the solution:
Go to "Start > Run". Enter: gpedit.msc
In the left pane, expand “Computer Configuration > Administrative Templates > Network > SSL Configuration Settings”
In the right pane, right click “SSL Cipher Suite Order” and choose “Edit”
Save the text inside “SSL Chiper Suite” field to a Notepad for backup
Select “Not Configured”
Click “OK”
Restart the server (gpupdate doesn’t enforce this setting. You should restart the server)
Source: The request is not supported (Exception from HRESULT: 0x80070032)

Visual Studio 2015 RTM - Debugging not working

I have installed VS 2015 RTM (nothing else) and I'm unable to debug any solution, not matter if it's an existing one or a brand new one (created with VS 2015 and compiled against .Net Framework 4.6), it only opens a new tab in VS which is called Break Mode with the following text:
The application is in break mode
Your app has entered a break state, but no code is executing that is supported by the selected debug engine (for e.g. only native runtime code is executing).
And if I check the Debug --> Module Window:
VS2015Test.vshost.exe no symbols loaded (even if I click load symbol it does not work)
VS2015Test.exe symbols loaded
And it also doesn't show the output on the console(it's a console application that just has the following lines of code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("TEST");
Console.ReadKey();
}
}
I tried to reinstall VS 2015, restarted the computer, deleted all files in %temp%/AppData/Microsoft/Visual Studio/14, started VS in Admin Mode but nothing seems to work.
One thing which makes debugging working is this option:
Tools --> Options --> Debugging --> Use Managed Compability Mode
^^But that can't be the solution to use an old/legacy mode.
BTW: Debugging in VS 2013 is working fine.
Any help would be appreciated.
In my case this solution is useful:
Solution: Disable the "Just My Code" option in the Debugging/General settings.
Reference: c-sharpcorner
I was having this same problem with VS2015. I reset the settings, as suggested but still had trouble.
What I had to do to fix it was check "Use Managed Compatibility Mode" and "Use Native Compatibility Mode". Not sure which of those 2 is necessary but checking both and I no longer get the Break Mode issue.
I had a very similar issue recently, related to debugging settings.
Firstly have you tried resetting all your settings? I think it may be related to that as you say it is project independent and you've deleted all application data.
Tools-> Import and Export Settings Wizard -> Reset all settings
Don't worry, it gives you the option to save current settings.
Secondly if this fails, I would suggest looking at the event log.
Entering break mode would suggest that the DE (debug engine) is sending a synchronised stop event to visual studio like IDebugExceptionEvent2. I would take a look at the event log for exceptions like failures in loading referenced assemblies (like .NET runtimes, etc) or environment access restrictions.
Something is telling the debugger to stop your running application, its just a case of finding it.
Thought I would post this in case it helps anyone. I installed a clean Win 10 and Visual Studio 2015, tried to debug an existing solution and had problems. Followed some advice listed here and other places but none worked.
How I got the debugging to work as normal was to change the Solution Configuration just below the menus. I had it set previously to Release mode, changed this to Debug and then cleaned/recompiled and hey presto, debugging started working as normal. See the image for info:
My solution suddenly stopped to work in debug.
I received a message during debug.
[Window Title]
Microsoft Visual Studio
[Main Instruction]
You are debugging a Release build of NettoProWin.exe. Using Just My Code with Release builds using compiler optimizations results in a degraded debugging experience (e.g. breakpoints will not be hit).
[Stop Debugging] [Disable Just My Code and Continue] [Continue Debugging] [Continue Debugging (Don't Ask Again)]
I chose to continue to debug, but it still did not work.
The solution was simple. It is necessary in the project properties -> in the build section -> remote the check "Optimiz code"
Check the "Code Type" before attaching to a Process. For example, I had to switch from CoreCLR to v4.*
In my case,
I have changed Platform from x86 to x64 in Debug Configuration Manager. It worked for me.
I disabled avast file system shield and then all worked normal again.
avast-setting wheel= active protections- top button off.
Same is required to publish projects. A real nightmare
I had a problem similar to this when trying to use Debugger.Launch to debug a web application: the JIT Debugger Selection window never appeared. I knew it wasn't a problem with VS debugging mechanism itself because it fired just fine with a console app.
Eventually a colleague mentioned a "global debugger registry setting" which set off a light bulb.
I was using Microsoft's DebugDiag some months ago to troubleshoot IIS crashing, and I had a rule registered to capture IIS crash dumps, which obviously (in retrospect) registered the Debug Diagnostic Service as the debugger for w3wp (IIS worker process).
Removing the rule in DebugDiag, or stopping the Debug Diagnostic Service ("C:\Program Files\DebugDiag\DbgSvc.exe") re-enabled Visual Studio's JIT debugging.
Hope this helps someone.
Uhg. I hit the bottom of this page so I started ripping apart my project. I found a solution for my particular problem.
My Issue: I couldn't hit the break-point inside a threaded process. Nothing fancy, I'm just starting a new thread in a console app and the debugger wasn't stopping on the break points. I noticed the thread was being created but it was getting hung up in .Net Framework external calls and specifically the ThreadStart_Context. That explains why my breakpoints never got hit because the .Net Framework is getting hung up something.
The Problem: I found that I could solve this by changing my startup code. For whatever reason, I had a program.cs file that contained Main() and was inside the Program class as you would expect for a console app. Inside Main(), I was instantiating another class via this code;
new SecondClass();
This normally works fine and I have a bunch of other projects with Threaded calls where it works fine (well, I haven't debugged them for some time so perhaps a service pack came along and is causing this regression).
The Solution: Move Main() into my SecondClass and instead of invoking the SecondClass constructor via 'new SecondClass()', update the SecondClass constructor to be a standard static method and then call it from Main. After making those changes, I am able to debug the thread once again.
Hope this helps.
After installtion of vs 2017,while debugging the solution,there was an error like "Webkit has stopped functioning correctly; Visual Studio will not be able to debug your app any further.",this makes unable to proceed the debugging.To resolve this issue,Go to Tools->Options->Debugging->General then disable the javascript debugging for asp.net
I have had similar issues on my svc application run on visual studio 2015, the solution was to change solution platform from "Any CPU" to "x86", if you cannot see the x86 option then click on "Configuration Manager" and go to your target project and change the platform, you'll need to select the dropdown and click "New", on the pop up, click the drop down list under "new platform" and select x86, save your changes and rebuild(See attached)
Stop debugging.
Edit csproj.user file
Find section wrote below:
<SilverlightDebugging>True</SilverlightDebugging>
Change Value to "False"
Unload and reload your project in Visual Studio.
Sometimes it needed to close Visual Studio.
A friend had the same problem, he couln't debug in VS2015 but it was ok in VS2013. (our project is in .Net v4.0)
We have found that it was the "Code Type" option in Debug / Attach to Process that was set to "Managed (v3.5, v3.0, v2.0)" instead of "Managed (v4.5, v4.0)"
I had this issue, and none of the (myriad of) posts on here helped. Most people point towards settings, or options, turning on Debug mode, etc. All of this I had in place already (I knew it wasn't that as this was working fine yesterday).
For me it turned out to be a referencing issue, a combination of DLLs that were included were to blame. I can't say exactly what the issue was, but I have a couple of classes that extended base classes from another project, an implemented interface that itself extends from another interface, etc.
The acid test was to create a new class (in my case, a Unit Test) within the same project as the one failing to Debug, then create an empty method and set a breakpoint on it. This worked, which further validated the fact my settings/options/etc were good. I then copied in the body of the method that failed to Debug, and sure enough the new method starts failing too.
In the end I removed all references, and commented out all the lines in my method. Adding them back in one by one, checking Debug at each step, until I found the culprit. I obviously had a rogue reference in there somewhere...
We had this issue, after trying all other options such as deleting .vs folder, Renaming IISExpress folder name, Updating various setting on properties etc it did not work. What worked though, was uninstalling IISExpress 10.0, and Reinstalling it along with turning all IIS related features on from Windows Features. Hope this helps someone.
I changed my Platform Target from "Any CPU" to "x64".
Setting available at : Project Properties -> Build -> General: "Platform Target"
I use VS 2015.
I found I had to go to the project settings -> web, and tick the Enable Edit and Continue checkbox. I cannot say why it was unchecked to begin with, but this solved it for me.
from Solution Explorer -> Web -> Properties
select Build tab -> Configuration combobox:
Just change your Configuration from "Release" to "Active (Debug)"
In my case it was due to the project Target platforms were different.
Consider : ProjectA (Entry) --> ProjectB
ProjectA's platform in properties was set to x64.
And ProjectB's platform was 'AnyCPU'.
So after setting ProjectB's target platform to x64 this issue got fixed.
Note: It's just that Target Platform has to be in sync be it x64 or
'Any CPU'
In my case, I found a hint in the output window that the exception that stopped the debugger was a ContextSwitchDeadlock Exception, which is checked by default in the Exception Settings. This Exception typically occurs after 60 seconds in Console applications. I just unchecked the exception and everything worked fine.
I had this same issue. In my case, the dll I was trying to debug was installed in the GAC. If your debugging breakpoint hits when you aren't referencing any object in the target assembly, but doesn't when you reference the assembly, this may be the case for you.
I had this problem after deinstallation of RemObjects Elements 8.3 Trial version. Reinstall Elements 8.3 is a quick bugfix.
I got in this issue as well. I'm using VS 2015 (Update 3) on Windows 10 and I was trying to debug a Windows Forms Application. None of the suggestion worked for me. In my case I had to disable IntelliTrace:
Tools > Options > IntelliTrace
I dont know the reason why, but it worked. I found out the root of the problem when I opened the Resource Monitor (from Windows Task Manager) and I realized that IntelliTrace process was reading a tons of data. I suspect this was causing locks in vshost process, because this one was consuming 100% of a cpu core.
I hade the same problem. After trying the other solutions here without luck, I had to repair the installation through the installer.
Control Panel > Programs > Programs and Features
Then scroll down to Microsoft Visual Studio, right click it, then "Change". Then at the bottom of the window, click Repair. The repair process will take a decent amount of time, and at the end you will have to restart your computer.
This fixed the problem to me, and I hopes it will help you.

Windows Forms Application won't run on another PC

I've got a huge problem. I was writting an WFA + C++/CLI DLL application. Everything worked fine until I had to sent it to my friend. Every time he executed the exe file from bin/debug (+additional dll and xml files) nothing happened (he doesn't have Visual Studio installed). The problem doesn't occur to me. On my PC everything works fine.
What i noticed (after couple of hours looking up the solution) is that somehow this is the critical moment :
log = new StreamWriter("log.txt", true);
log.WriteLine("3c");
log.Close();
materialTypeComboBox.SelectedIndex = 0;
log = new StreamWriter("log.txt", true);
log.WriteLine("3d");
log.Close();
"3c" is the last line in my simple log file every time my friend execute this. If I comment this, app crashes on
foreach (RadioButton item in someGroupBox.Controls.OfType<RadioButton>()) { ... }
Seems like WFA's Controls cause that effect, but how is it possible?
I tried changing target framework form 3.5 to 4.5.1, building project in Debug and Relase mode, x86, x64, using a installShield projects (I thought I missed some references while sending him the app), one-click installer, creating empty project and paste sources - without any success.
How could it be? No exception, no message box, nothing. Just click and nothing happens.
Does anybody know some solution?
Windows Forms is renown for it's ability to silently swallow exceptions. I would highly recommend logging unhandled exceptions. To log unhandled exceptions, do the following:
Application.ThreadException += new ThreadExceptionEventHandler(UnhandledUIException);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledException);
private static void UnhandledUIException(object sender, ThreadExceptionEventArgs e)
{
// Log exception
}
private static void UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// Log exception
}
Info: http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx
Info: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx
SOLVED:
The problem was with the DLL - with Dependency Walker I discovered that my DLL needs msvcr120.dll to run, and even including it to project output folder did not help, and also msvcr causes the x84/x64 mismatch error. Recompiling DLL solved problem:
Statically Linking the DLLs
Make sure you resolve it for both Release and Debug. The steps are slightly different.
Release
In Visual Studio, I went to the project Properties. I changed
my Configuration to Release. I went under Configuration Properties |
C/C++ | Code Generation Look at the Runtime Library setting. It is
set to this: Multi-threaded DLL (/MD) Change it to this:
Multi-threaded (/MT) Rebuild. Debug Almost exactly the same as
release.
Debug
In Visual Studio, I went to the project Properties. I changed my
Configuration to Debug. I went under Configuration Properties | C/C++
| Code Generation Look at the Runtime Library setting. It is set to
this: Multi-threaded Debug DLL (/MDd) Change it to this:
Multi-threaded Debug (/MTd) Rebuild the debug
http://www.rhyous.com/2010/09/16/avoiding-the-msvcr100-dll-or-msvcr100d-dll/

Visual Studio 2008 stopped displaying errors

After some months of inactivity, I decided to work with Microsoft Visual Studio (C#) again.
After some clicks on "start debugging" I got windows error (I think svchost.exe has stopped working) and I don't know if this was relevant with what I'm about to say, but I'm not getting any errors when for example I'm calling an array out of bounds.
The program just doesn't execute the code assossiated with the error (I've noticed the array and file I/O problems) but continues to run normally which is driving me crazy because I have to click "start debugging" after I write each line of code just to be sure I'm correct.
So, Debug > Exceptions, it's chaos over there and I haven't touched it before.
Any help would be appreciated.
EDIT: I've restarted 3 times my computer and did the Clean and Rebuild just now (the project) and nothing changed.
EDIT2: Sorry if it's confusing, here are some new info:
public partial class frmMain : Form
{
PictureBox[] pic = new PictureBox[120];
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
// Creating pictureboxes
for (int i = 1; i <= 199; i++) //199 instead of 120 or 119 and the rest of the for isn't executed plus no error or warning displayed.
{
pic[i] = new PictureBox();
EDIT3: Below is another example. If I try to read a non-existent file without the try-catch sequence, then the whole pic[] matrix is like being unloaded from the memory when the program runs.
pic[i].Image = Image.FromFile("H:\\My Pictures\\" + i + ".jpg");
EDIT4: Thank you for your time. I tried "Release" instead of "Debug" and the problem was fixed for a while.
When I decided to press "Continue" instead of "Break" on the "OutofRangeException", Windows popped this message: "Windows had to run the program on compatibility mode". Now when I press "start debugging" it's like before...
It sounds like you may be dealing with this issue:
Something swallowing up unhandled exceptions?
Basically, when building on 64 bit machines, exceptions are sometimes swallowed.
I believe there may be a hotfix for it, as outlined here:
https://connect.microsoft.com/VisualStudio/feedback/details/357311/silent-exceptions-on-x64-development-machines
Here is the hotfix: http://support.microsoft.com/kb/976038
Otherwise, try setting the target build to x86 rather than x64 or "Any CPU". Also try running in release mode and see if the exceptions occur.
If this is not the problem, then you may need to re-install Visual Studio. If you're using Visual Studio Express, why not upgrade to a more recent version than 2008?
EDIT:
Also, try applying all the service packs and patches to the OS as well. If you're using Windows 7, you should be on SP1 for sure. You should also make sure you are using Visual Studio 2008 SP1 and all patches.
You have hit a known misfeature in Windows / .Net / C# / Wow64, that happens when Form.Load event handlers throw exceptions.
VS2010 does not show unhandled exception message in a WinForms Application on a 64-bit version of Windows
From Hans Passant's answer:
This is a nasty problem induced by the Windows wow64 emulation layer
that allows 32-bit code to run on the 64-bit version of Windows. It
swallows exceptions in the code that triggers the Load event.
Preventing the debugger from seeing it and stepping in. This is
apparently hard to fix, the Windows and DevDiv groups at Microsoft are
pointing fingers back and forth. DevDiv can't do anything about it,
Windows thinks it is the correct behavior, mysteriously as that
sounds. It is only a problem with a debugger attached, your code will
bomb as usual without one.

vshost.exe keeps accessing my .dll and I can't update it when I build it

I have set an output folder for my .dll project though the Project Properties, which I call "Output".
The problem is, from an empty Output folder, the first time I Build the project, it's fine. The second time, I get the following error:
Error 328 Unable to copy file "obj\Release\MyLibrary.dll" to
"......\Output\Release\MyLibrary.dll". The process cannot access the
file '......\Output\Release\MyLibrary.dll' because it is being used
by another process.
The "another process" is the vshost.exe from Visual Studio. Since it keeps acessing MyLibrary.dll, it can't be deleted or replaced, thus why the error. This keeps the MyLibrary.dll on the Output folder not updated. However I have other .dll projects in my solution in which this does'nt happen.
The solution I have used so far to update it is to close the VS (thus closing vshost.exe), then run a .bat file which deletes the file Output\Release\MyLibrary.dll, then open the VS again and Rebuild it's project.
I know little of what exactly vshost.exe does, so I have no idea from where to start to clear this problem from the root. I don't know why this happens to a specific .dll. I appreciate any idea that helps me investigate why this happens.
vshost.exe is the Visual Studio Hosting process. It is a custom CLR host that loads your EXE and makes debugging easier. You can turn it off, that has very few side-effects. Project + Properties, Debugging tab, untick the "Enable the Visual Studio hosting process" option.
You are more likely to find the real problem in your program now. With the most common issue that your program doesn't quit when you ask it to. You will still get a build error, you'll now see your own EXE fingered as the one that keeps a lock on the DLL. You will also see it back in the Task Manager's Process tab. Which also allows you to kill it.
It isn't that clear to me how programmers recreate this problem. Pressing Ctrl+F5 instead of F5 certainly will do this, always press F5 to immediately attach the debugger when you start the program. Using Debugger + Stop Debugging will now reliable stop the program. You can otherwise use Tools + Attach to Process to get a debugger attached again later to find out what your program is doing.
Anti-malware is a common scourge worth mentioning, they get way too excited when they see an executable file appear from nowhere. If you use Avast then just uninstall it completely, it is quite incompatible with VS.

Categories

Resources