Is there an interface wrapper around the Task Para

2019-05-10 11:36发布

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.

2条回答
The star\"
2楼-- · 2019-05-10 11:58

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.

查看更多
聊天终结者
3楼-- · 2019-05-10 12:09

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.

查看更多
登录 后发表回答