Could not write to output file 'c:\xxxx\obj\x86\Debug\yyyy.exe' -- 'The process cannot access the file because it is being used by another process

While compiling in Visual Studio 2012, I was continually getting the following error after every attempt to compile:

Could not write to output file 'c:\xxxx\obj\x86\Debug\yyyy.exe' -- 'The process cannot access the file because it is being used by another process.

For a brief moment of time this file was locked and inaccessible to the IDE. Naturally, I first checked that the Indexing Service or an antivirus app wasn't locking the file. I disabled both and yet the error still occurred after every compile attempt. Closing Visual Studio and rebooting did absolutely nothing.

In fact, I couldn't find any kind of lock on the file and could easily delete it. Subsequently, compiling would succeed, but any time I compiled again it would just lock up once more. Every post I read was indicating that some external process wasn't giving up control of this file, but my gut was telling me the lock was as a result of the compilation itself.

Using Windows Sysinternals Process Monitor I was able to record all access performed on this file.

First MSBuild.exe took a crack at this file, operating on it repeatedly. No issue there.

Sharing violation

Then Csc.exe began using it, initially with success, then later the error "FILE LOCKED WITH ONLY READERS" occurred, ultimately ending with the error "SHARING VIOLATION".

Why was the compiler locking access to the compiled .exe?

When I checked the list of references for each project in the solution, I discovered one of my projects (the one leading to the yyyy.exe that was failing to compile) had a reference to itself! Not sure how a reference to the very same project was added... maybe as a result of some refactoring while using ReSharper?

So if you come across an error about an access violation during compile and it doesn't actually appear to be due to another application (such as an antivirus) grabbing the file before compilation is complete, double-check that your project isn't accidentally referencing itself.