multithreading - Synchronizing a collection of shared resources in C# -


i have static collection of shared resources (text processor classes) in c# application respond keywords. each processor stateful, , not work in multithreaded context. looking way organize these can make thread-safe access them.

for instance, embed sync object in each processor

public abstract class textprocessor {     protected internal readonly object sync = new object();      public abstract void run( string text ); }  public class documentprocessor {     private static dictionary<string,textprocessor> s_procmap = ...;      public void run( string [] words1, string[] words2 )     {         threadpool.queueuserworkitem( process, words1 );         threadpool.queueuserworkitem( process, words2 );     }      private void process( object arg )     {         foreach( var word in words )         {             var proc = s_processor[word];             lock( proc.sync )             {                 proc.run( word );             }         }     } 

assuming can't rewrite processors stateless (which option last resort due volume of refactoring), there better way express this?

if don't want change processor... make wrapper.

public class procwrapper {   private textprocessor _proc;   private actionblock<string> _actblock;    public procwrapper(textprocessor proc)   {     _proc = proc;      _actblock = new actionblock<string[]>(word=>     {       _proc.run(word);     });   }    public void addword(string words)   {     _actblock.post(word);   }    public void waitforcompletion()   {     _actblock.completion.wait();   } } 

and use similar how had before:

dictionary<string,procwrapper> s_procmap = ...;  void run( string [] words ) {   // note: assumes same thread access s_procmap.   foreach(var word in words)     s_procmap[word].addword(word); } 

i think close you're looking for.

take @ http://msdn.microsoft.com/en-us/library/hh228603.aspx more info on dataflow tpl , http://msdn.microsoft.com/en-us/library/hh194684.aspx info specific actionblock<t>.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -