3 simple JobDispatcher

In a previous post, I implemented a JobDispatcher using a queue and a BackgroundWorker. There are 3 simple JobDispatcher I'd like to implement now:

  • a NullJobDispatcher, that, basically does nothing,
  • a SynchronousJobDispatcher, that execute the job when it is dispatched,
  • a ReactorJobDispatcher, that uses the ThreadPool.

If you read Marc' blog, you won't be interrested by the last two.

The NullJobDispatcher

class NullJobDispatcher : JobDispatcher
{
    public override void Dispatch(IJob job) {
    }
}

Doing nothing could be interesting for 2 reasons:

  1. you can use this special value to initialize the dispatcher in your, so you do not have to test if a dispatcher is null or not before using it;
  2. you can use it when testing parts of your code that do not require that you actually execute the jobs.

You should not have to instantiate this class, so it is best to implement it as an nested class of the `JobDispatcher` abstract class and add a static property that will return its sole instance.

The SynchronousJobDispatcher

public class SynchronousJobDispatcher : JobDispatcher
{
    public override void Dispatch(IJob job) {
        if (job == null) {
            throw new ArgumentNullException("job");
        }

        job.Execute(this);
    }
}

Being synchronous is a little bit contrary to the philosophy of the jobs dispatcher. Nevertheless, it is sometimes handy when debugging.

The ReactorJobDispatcher

public class ReactorJobDispatcher : JobDispatcher
{
    #region JobDispatcher Membres

    public override void Dispatch(IJob job) {
        if (job == null) {
            throw new ArgumentNullException("job");
        }

        ThreadPool.QueueUserWorkItem(DoJob, job);
    }

    private void DoJob(object obj) {
        ((IJob)obj).Execute(this);
    }
}

This last dispatcher queues the job in the thread pool queue.

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.