Dynamic MEF isn’t thread safe by nature


one comment

Dynamic MEF isn’t thread safe by nature

this post focus a pitfall which you should be aware in order to avoid sporadic crashes.

In general most of MEF operation are operate once at the application initialization stage,

and it normally happens on a single thread.


this may not be true when you need to dynamically load MEF parts (using GetExportedValue or SatisfyImportsOnce).


unfortunately MEF underline is using non concurrent dictionary which is not thread safe for the above operation implementation.

therefore the following code will crash sporadically.

Code Snippet
  1. [Export] // exported type which will instantiate using MEF
  2. public class ExportedType {}
  4. public class Program
  5. {
  6.     static void Main(string[] args)
  7.     {
  8.         var catalog = new AssemblyCatalog (typeof(Program).Assembly);
  9.         var container = new CompositionContainer(catalog);
  11.         for (int i = 0; i < 100; i++)
  12.         {
  13.             new Thread(() =>
  14.                 {   // get the exported part dynamically (instantiate by MEF)
  15.                     container.GetExportedValue<ExportedType>();
  16.                 }).Start();
  17.         }
  18.     }
  19. }

line 15: GetExportedValue call is a non protected critical section.



whenever using dynamic MEF techniques you should put a critical section synchronization over it.



Eran Stiller was the first one who’s point my intention to this issue.


kick it on DotNetKicks.com Shout it

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


one comment

  1. Jammer2016/03/18 ב 21:02

    Seems like the page where you link too for the code is no longer there …