Dynamic MEF isn’t thread safe by nature

2010/12/04

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 {}
  3.  
  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);
  10.  
  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.

 

Summary

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

 

the code sample can be found here.

 

Credits

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

 

kick it on DotNetKicks.com Shout it

Digg This
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=""> <strike> <strong>