Search code examples
.netroslynroslyn-code-analysis

Is it safe to use different AdhocWorkspace instances concurrently?


I am facing a case where I would like to use different instances (not one shared instance) of Microsoft.CodeAnalysis.AdhocWorkspace (docs) concurrently in multiple threads (=> one seperate instance per thread).

One thing which struck me, while looking at the default-constructor of the AdhocWorkspace, was that it's always using a static MefHostServices instance behind the scenes:

public AdhocWorkspace() : this(Host.Mef.MefHostServices.DefaultHost)

This made me curious, and I did a bit of research, to find out whether several concurrent AdhocWorkspaces could cause any problems.

Results:

  • I couldn't find any documentation which is either explicitly stating that it's safe or not.
  • I found a few old github issues like this and this, which are discussing concurrency problems. Especially the latter one, sounds like it's ok as long as we use just one host service (which seems to be the case with the default constructor), although I'm not sure if this is even relevant for my case.
  • I actually tried out to use a lot of AdhocWorkspaces in parallel (adding documents, projects and compiling) and did not experience any problems so far.

Conclusion: Although it looks good so far I would be interested in how this was actually designed to work. Especially in case of possible race-conditions I would not like to rely on a quick test and a bit of research without a clear result.

Maybe someone can point me to a relevant piece of documentation or code? Or even a roslyn team member can bring some clarification?

Note: I am not really familiar with MEF, so maybe it would be easier for me to answer this question myself, if I had the lacking MEF knowledge.


Solution

  • It's absolutely fine to use multiple Workspaces at once. The services that are shared from the host services are expected to either be stateless (so no race conditions to worry about), or if they are maintaining state do so safely.