3

I asked this question a while ago. I now know it is a Bad Idea and that encapsulating the scheduling and running of tasks should be abstracted so that one can pass in a synchronous scheduler from the unit tests.

I've currently got code that uses the Task Parallel Library (TPL) and I'd like to inject something like ITaskScheduler into my types to extract out responsibility of scheduling and enable me to pass in a synchronous alternative in my tests.

Does such a thing exist? I'm looking for something that wraps Task.Factory.StartNew and Task.ContinueWith. I don't suppose it's not too much work to roll my own, but I'm sure there's lots of little gotchas and I don't really want to spend time doing it if there's one already available.

1
  • 1
    I don't think that there could by any gotchas as far as you put the Task API straight behind an interface. Using that interface shouldn't be much different to using the API directly. Aug 23, 2010 at 13:00

2 Answers 2

5

Substituting the Task class is hard, even if you inherit a new class from Task: since TaskScheduler and TaskFactory aren't generic on Task it will not help much at all.

A better approach in my experience is to use your own TaskScheduler class (inherited from TaskScheduler). You can pass it into a TaskFactory constructor and then use that TaskFactory throughout.

Now for testing you can use a different TaskScheduler with varying degrees of parallelism (down to 1 thread if you want) and you can add extra logging to your TaskScheduler class to log each task as it starts and finishes.

2

You could define such an interface and wrap the actual library classes inside a facade that implements the interface. For testing, swap your Facade against a mock object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.