views:

460

answers:

2

I Hope I used the right term

What I'm aiming for is something like this (I realise it doesn't work that way):

private bool someBool = false;

BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(DoLengthyTask);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
 ()=>
  {
   someBool = true;
   Logger.Info("Finished");
  }
)

The important part being the RunWorkerCompletedEventHandler being defined within the scope of the original caller and by that having access to the caller's variables.

Is this possible? Would it generate possible race conditions on the someBool?

+3  A: 

It doesn't work in your example, since the complete delegate should receive 2 parameters:

private bool someBool = false;

BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(DoLengthyTask);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        (sender, e)=>
                {
                        someBool = true;
                        Logger.Info("Finished");
                }
)
Alex Reitbort
While true, I'm not sure that goes any way to answering the actual question(s)...
Marc Gravell
Now only the race conditions issue remains.
borisCallens
A: 

It all depends on what else uses the bool.

In particular, it the bool truly a field (as suggested by the "private"), or is it a variable? There is a difference, as you can mark a field as volatile (but not a variable).

However, my gut feel is that you should be using synchronization such as Monitor, perhaps with pulsing etc - or a gate such as ManualResetEvent.

Without either synchronization or volatile, it is possible for another thread to not see changes to the variable - but we really can't say more without the other half of the code...

Marc Gravell
I fear there is no other half. It was a fictuous example in an effort to break a bigger problem I can't solve into smaller sub-problems.For the whole picture, please refer to http://stackoverflow.com/questions/594230/wait-for-two-threads-to-finish/594238#594238
borisCallens