I’m using the TPL but I’m finding it tricky unit testing code that uses it.
I’m trying to not introduce a wrapper over it as I feel it could introduce issues.
I understand that you can set processor affinity in the TPL, but what’d be really nice is to set a thread maximum (probably per app-domain). Therefore, when setting the thread maximum to 1, the TPL would be forced to use whatever thread it was used on.
What do you think? Is this possible (I’m pretty sure it’s not), and should it be possible?
Edit: here’s an example
public class Foo
{
public Foo( )
{
Task.Factory.StartNew( () => somethingLong( ) )
.ContinueWith( a => Bar = 1 ) ;
}
}
[Test] public void Foo_should_set_Bar_to_1( )
{
Assert.Equal(1, new Foo( ).Bar ) ;
}
The test probably won’t pass unless I introduce a delay. I’d like to have something like Task.MaximumThreads=1 so that the TPL will run serially.
You could create your own
TaskSchedulerclass deriving fromTaskScheduler, pass that into theTaskFactory. Now you can have anyTaskobjects that you create run against that scheduler.No need to set it to use one thread.
Then, right before your asserts, just call
Dispose()on it. Internally it will do something like this if you follow the samples out there for writing aTaskScheduler:-That will guarantee that all the Tasks have been run. Now you can move ahead with your Asserts.
You could also use
ContinueWith(...)to add assertions after a Task has run if you wanted to check progress as things were happening.