0

Environment: .NET 4.0 C#

I have multiple running generators async. They generate IResult object, check common criteria and push result to shared collection. Generators have to support cancellation and progress reports.

Here is a pseudo code:

private Dictionary<string, IResult> resultCollection;
private ICriteria criteria;
private bool isCancelled;

// Multiple Running Generators
private GeneratingAsync(ICriteria criteria)
{
    while (!isCancelled)
    {
        IResult result = GenerateResultAsync();

        if (CheckCriteria(result, criteria))
            OnResultAvailable(this, new ResultEventArgs(result));
        OnProgressChanged(this, new ProgressEventArgs(...));
    }
}

private void OnResultAvailable(object sender, ResultEventArgs e)
{
    // Push result object
    if(!resiltCollection.Contains(e.Id))
        resiltCollection.Add(e.Id, e.Result)
    ...
}

private void OnProgressChanged(object sender, ProgressEventArgs e)
{
    ...
}

In my current project I use one Generator implemented with BackGroundWorker. My question is what pattern to use for multiple async generators:

  • I read about Observer Design Pattern, but MS recommends it for one generator and multiple observers, which is not my case.
  • Event pattern
  • Reactive Extensions
  • ...

Also, can I use several BackGroundWorkers or it's better to use tasks?

Edit:

What is better for resultCollection: ConcurrentDictionary or Dictionary with properly locked AddResult() and GetResult() methods?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Miroslav Popov
  • 3,294
  • 4
  • 32
  • 55
  • I don't understand the problem that you are trying to solve. Can you describe more about that rather than how you think it should be solved? – Enigmativity Sep 23 '13 at 07:52
  • The problem is that I have to generate multiple objects async. These objects have to fulfill a predefined criteria. Once a object is generated and checked, it must be stored in a collection. So I need several generators to work simultaneously and to push results with cancellation and progress report. Result collection must be thread safe. – Miroslav Popov Sep 23 '13 at 07:58
  • Again, you're describing the solution and not the problem. What are you trying to solve? (Not how are you solving it.) – Enigmativity Sep 23 '13 at 14:07
  • @Enigmativity, I want to generate trading strategies for the Forex market. – Miroslav Popov Sep 23 '13 at 20:14
  • I don't want to sound difficult, but that's not really the problem, it's more like a title and not a description. – Enigmativity Sep 23 '13 at 21:47
  • I think the class you are looking for is [BlockingCollection](https://stackoverflow.com/a/40340027/2791540), which is essentially a thread-safe queue specialized for producer/consumer. – John Wu Oct 19 '19 at 07:20

0 Answers0