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.
Substituting the
Taskclass is hard, even if you inherit a new class fromTask: sinceTaskSchedulerandTaskFactoryaren’t generic onTaskit will not help much at all.A better approach in my experience is to use your own
TaskSchedulerclass (inherited fromTaskScheduler). You can pass it into aTaskFactoryconstructor and then use thatTaskFactorythroughout.Now for testing you can use a different
TaskSchedulerwith varying degrees of parallelism (down to 1 thread if you want) and you can add extra logging to yourTaskSchedulerclass to log each task as it starts and finishes.