I recently asked a developer to write a library using the new multithreading capabilities of .NET 4.0.
He's done a great job, but I'm concerned that the Task logic is repeated throughout the code and not nicely encapsulated.
I'm also concerned that this creates a problem when it comes to testing. Normally, I test by creating a seam in the code by creating an interface and a stub/mock object to run my tests against.
I suppose this is possible using this way of doing things. It just seems that the production code logic would be very different than the test logic.
Is the solution to make tests that are parallel as well, and just repeat the Task logic in them? Or have people thought up patterns where much of the Task handling logic can be encapsulated for easy duplication?
Thanks!
Task task = Task.Factory.StartNew(() =>
{
if(cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException();
}
if (_bookHeader.EncryptionType != 0)
{
throw new MobiException("The book is encrypted");
}
ExtractText();
partReady(66.66f);
}, cancellationToken);
Task opfTask = task.ContinueWith(antecedent =>
{
if (antecedent.Status != TaskStatus.Canceled)
{
OpfDocument opf = CreateOpf();
partReady(80);
MobiDocument book = new MobiDocument()
{
Contents = _mobiHtml,
Description = opf,
Header = _bookHeader,
Sections = _sections
};
Document = book;
GC.Collect();
partReady(100);
}
});
return opfTask;
}
I'd be surprised (but delighted) if it's possible to better the last 3 chapters of CLR via C# 3rd Ed by Richter for getting a great handle on the landscape of parallel stuff in .NET 4. (Just read Effective C#, Second Edition and can't say the same for it's coverage of TPL and PL)
One reason I feel this is relevant is that he talks a lot about how to make the code clean and maintainable (and some stuff in PowerThreading that he's used quite a bit). (And in the unlikely event you're not aware of the book, it's the CLR book to have, and the 3rd Ed is a significant upgrade of the 2nd Ed)
Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4
Updated samples for parallel programming
A Tour Through the Parallel Programming Samples for .NET 4
Parallel Programming with .NET
Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4