More Multi Threading

time to read 3 min | 571 words

Well, I improved on my multi threading code, but I was still not satisfied about the way it work, it created threads unnececarily, so I decided to improve it. Again, I'm using Udi Dahan's ThreadSafeQueue for multi threading.

The idea is based on what Udi Dahan had to say on the comments for my post, and is actually very simple, the queue host intellegent commands, and the working thread simply has to pull them out of the queue and execute them, one at a time.

Here is the working thread implementation:

public class ThreadedCommandExecutioner
{
 ILog logger = LogManager.GetLogger(typeof (ThreadedCommandExecutioner));
 private readonly IQueue queue;
 bool runThread;
 public ThreadedCommandExecutioner(IQueue queue)
 { 
  this.queue = queue;
  runThread = true;
 }
 public void Run()
 {
  ICommand cmd;
  while(RunThread)
  {
   cmd = (ICommand)queue.Dequeue();
   if (logger.IsDebugEnabled) logger.Debug("Running command: "+cmd.Name+". Command Info: "+cmd.Info);
   cmd.Execute();
  }
 }
 public bool RunThread
 {
  get { return runThread;}
  set { runThread = value; }
 }
}

Now the only thing that I need to do when I want to run a job in the working thread is to add a command to the queue. [Currently I've BuildProjectCommand & ExecuteQueryCommand]

The nice thing about this is that I can expand this to more threads without having to do much beyond spun those threads (or better, just use ThreadPool).

Testing this is a little bit tricky, because I'm not really interested in starting threads in my tests, I managed to get around it by using the  DelegatingConstraintWithArgs I'm not sure that this is a good thing, though. Suggestions?

By the way, I really do need to start using NCover again, I've done an extensive modification, and I didn't get nearly enough breaking tests. (It's all because of the UI, I swear :-)).