I need to synchronize access to a shared resource between projects built in MsBuild. In the past, when projects ran sequentially and in the same process, this was not a problem. But now when MsBuild can run project builds in several threads and several processes, I just can't find a way to achieve this.
Basically, what I want is that when my projects start to build, I can do some operation on the resource. And when they all have built to the end, I can do another operation.
If thought first that I could implement a custom task and have every project modify the build process, injecting the task before the build and after the build. But since they can run in parallel and even across processes, I seem to be out of option.
When trying to figure this out, the closest I came was when I found the BuildSubmission class in the Microsoft.Build.Execution namespace (http://msdn.microsoft.com/en-us/library/microsoft.build.execution.buildsubmission.aspx). But I can't find anything on how I'm suppose to interact with these classes from my custom tasks.
Any type of input or pointers in some direction would be highly appreciated!
/Per
You can implement your resource access in a custom MSBuild task and protect it by a named mutex (these can be used to synchronize separate processes). That is, the implementation will first acquire the mutex, check whether the resource needs to be touched or not, and only then will it perform its work on the resource and finally release the mutex. You can force this task to run either before or after the build using AfterTargets or BeforeTargets.
This way, if two projects that use this task reach the pre-build or post-build stage concurrently, only one of them will perform work on the resource while the other one waits. When the first project releases the mutex, the second one will acquire it, realize the job has already been done and immediately release the mutex, without touching the resource.
You should consider whether you want to use the same mutex or two different ones for the pre-build and post-build resource access (can they run concurrently?).