I am trying to practice manual dependency injection (no framework yet) to remove tight coupling in my code. This is just for practice - I don't have a specific implementation in mind.
So far simple constructor injection has worked fine.
However I cannot work out how to solve creating a tight coupling when one class must use another within a parallel loop. Example:
public class Processor
{
private IWorker worker;
public Processor(IWorker worker)
{
this.worker = worker;
}
public List<string> DoStuff()
{
var list = new List<string>();
for (int i = 0; i < 10; i++)
{
list.Add(worker.GetString());
}
return list;
}
public List<string> DoStuffInParallel()
{
var list = new System.Collections.Concurrent.ConcurrentBag<string>();
Parallel.For(0, 10, i =>
{
//is there any trivial way to avoid this??
list.Add(new Worker().GetString());
});
return list.ToList();
}
}
public class Worker : IWorker
{
public string GetString()
{
//pretend this relies on some instance variable, so it not threadsafe
return "a string";
}
}
Avoiding the obvious fact that a parallel loop will be slower than a standard loop in the above case, how could i write the Processor.DoStuffInParallel()
method to avoid the current hard dependency on the Worker
class?