tags:

views:

52

answers:

1

Suppose I have a MEF composition like this:

public class Composition
{
    [ImportMany(AllowRecomposition = true)]
    IEnumerable<ILongRunningProcess> Processes { get; set; }

    public static void Main(string[] args)
    {
         var composition = new Composition();
         using (var catalog = new DirectoryCatalog("."))
         {
             using (var container = new CompositionContainer(catalog)
             {
                 container.SatisfyImportsOnce(composition);
                 //Fire off long running processes in response to stimuli
             }
         }
    }
}

According to the documentation I've seen, I "have to consider thread-safety when using Recomposition."[MSDN]

Obviously for the case where I removed a type, I need to make sure that my long-running process can be garbage-collected safely. But for types that existed before the recomposition and still exist after the recomposition, will I get new instances back for the contents of Processes whenever recomposition occurs, or is MEF able to preserve existing instances of imports when a catalog is recomposed?

Based on the above article's suggestion that for ICollection<T> MEF will use the Clear() and Add(T) methods, I'm not hopeful, but I'd like to know for certain before I go write the synchronization code.

EDIT I just realized I can't use this in a static method; I've updated the code accordingly :)

A: 

You will get the same instances back unless the types with the ILongRunningProcess exports on them have the part creation policy set to NonShared.

This isn't really a thread-safety issue though. You do want to make sure that when recomposition occurs, nothing is accessing the MEF container (which includes things like accessing the Value property of a Lazy provided by MEF). So if your long running process is running on a different thread and it has its own imports, you can have threading problems.

Daniel Plaisted
What I'm implying with the term "thread-safe" is that I want to make sure I have a way to stop these processes deterministically so that their processing can be resumed by the next instance. There may be any number of them running when the catalog changes, and their work needs to be "resumable". I suppose that doesn't fit the classical definition. I'll try to come up with a better question title.
arootbeer