I am in an annoying situation where the visual studio debugger does not clean itself up after the debugging session is completed. Therefore, devenv.exe retains the lock of the executable file, and I cannot rebuild the project due to a terrible error:
Error 1 Failed to copy the 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 can be fixed by restarting visual studio, but by restarting my entire IDE after each startup cycle, not exactly contributing to an excellent coding environment. Build -> Clean does not help.
I searched for this error and although the symptom seems quite common, the underlying cause varies. First of all, I would like to know, in order of importance:
- Is there any quick way for a file to be unlocked without restarting the visual studio?
- Prohibition of which protective programming methods should be used to prevent this?
- What exactly happens behind the scenes in the example below, because of which the debugger does not release?
The following is an example of the code that will cause this symptom.
class Program
{
static void Main(string[] args)
{
var f1 = new Form1();
f1.Dir = "asdf";
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private FileSystemWatcher fsw;
public string Dir
{
get { return fsw.Path;}
set
{
fsw = new FileSystemWatcher(value);
fsw.EnableRaisingEvents = true;
throw new Exception("asdf");
}
}
~Form1()
{
if (fsw != null)
fsw.Dispose();
}
}
Playback:
- Run the program. Normally use the Visual Studio 2008 debugger.
- Stop debugging when an exception is thrown.
- Change the source code and try to restore.
Edit: kind decision:
public Form1()
{
InitializeComponent();
this.Closing += (sender, args) =>
{
if (watcher != null)
watcher.Dispose();
};
}
I'm still wondering why this works and when placed in the destructor, no.