Dependency injection with parallel processing

I am trying to apply manual dependency injection (no frame) to remove the hard link in my code. It's just for practice - I don't have a specific implementation.

So far, a simple constructor installation has worked fine.

However, I cannot decide how to solve the problem of creating a tight connection when one class should use another in 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 can I write a method Processor.DoStuffInParallel()to avoid the current hard class dependency Worker?

+4
source share
1 answer

, factory, :

public List<string> DoStuffInParallel(IWorkerFactory factory)
{
    var list = new System.Collections.Concurrent.ConcurrentBag<string>();

    Parallel.For(0, 10, i => 
    { 
        list.Add(factory.Create().GetString());
    });
    return list.ToList();
}

factory , Create() .

, , - (, ConcurrentBag). - bag, Parallel.For localinit/localFinally, / localFinally.

Edit
Re: factory ConcurrentBag<String>? IMO, , ConcurrentBag - , . , , :

return Enumerable.Range(0, 10)
                 .Select(i => factory.Create().GetString())
                 .ToList();

. - .

public IList<string> DoStuffInParallel IEnumerable<string> ( /). Worker, , , .

+4

Source: https://habr.com/ru/post/1545379/


All Articles