我问this提问前一阵子的。我现在知道这是一个坏主意,而且封装的调度和任务运行的需要抽象这样就可以通过从单元测试的同步调度。
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.
我目前得到一个使用任务并行库(TPL),我想是这样
ITaskScheduler
进入我的类型注入提取出调度的责任,使我能够传递在我的测试同步替代
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.
有没有这样的事情存在吗?我在找的东西,包装 Task.Factory.StartNew
和 Task.ContinueWith
。我不认为它没有太多的工作推出自己的,但我敢肯定有很多小的陷阱的,我真的不想花时间做,如果有一个已经上市。
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.
代入工作
类是硬的,即使你继承一个新的类工作
:因为的TaskScheduler
和 TaskFactory
不是一般的工作
将没有多大帮助的。
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.
在我的经验,更好的方法是用你自己的的TaskScheduler
类(从的TaskScheduler
继承)。你可以把它传递到 TaskFactory
构造函数,然后使用 TaskFactory
贯穿始终。
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.
现在测试你可以使用不同的的TaskScheduler
有不同程度的并行性(如果你想降低到1线),你可以添加额外的记录到你的的TaskScheduler
类,因为它开始和结束记录每个任务。
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.