views:

245

answers:

3

I'm creating an array of BackgroundWorker that shares one event handler like this:

BackgroundWorker[] workers = new BackgroundWorker[files.length];

for(int i = o; i<files.length; i++)
{
      workers[i] = new BackgroundWorker();
      workers[i].DoWork += new DoWorkEventHandler(worker_DoWork);
      workers[i].RunWorkerCompleted += newRunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
      workers[i].RunWorkerAsync(files[i]);
}

All workers are sharing the same event handler which does same thing only with different argument and result like this:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
         e.Result = ComputeSomething(e.Argument.ToString());
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
            resultArray.Add(e.Result);
}

private int ComputeSomething(string file)
{
         ...
         return number;
}

obviously in the code, I'm trying to make a list of BackgroundWorker that runs asyncronously but when I checked the results, some of them are incorrect. I'm guessing that the value of "e.result" were replaced by other workers since they share the same event handler if that is the case then i would like to create Individual event handlers for each BackgroundWorker so that the value of e.result won't get replaced. How will i do that?

+7  A: 

Try synchronizing the access to resultArray:


private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    lock(resultArray)
     resultArray.Add(e.Result);
}
Henrik
i added the lock and it is working now. thanks.
murasaki5
+1  A: 

Sharing the same event handler method shouldn't be a problem - it's the BackgroundWorker which provides the "e" in which you store the result.

On the other hand, you are accessing resultArray from multiple threads. That could be causing a problem. What sort of errors are you seeing in the results? Other than the way you're combining the results at the end, I'd expect it to be okay.

Jon Skeet
+1  A: 

I don't see how e.Result could be replaced by other workers. When you say some results are incorrect, do you mean the value is wrong, that there's no value at all, or maybe some results are duplicated while others disappear? It seems to me you should put a synclock when adding to resultsArray to make sure it's thread-safe.

Fermin Saez