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?