Boris Callens
Boris Callens

Reputation: 93367

Define backgroundworker's RunWorkerCompleted with an anonymous method?

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?

Upvotes: 2

Views: 2731

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1063884

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...

Upvotes: 0

Alex Reitbort
Alex Reitbort

Reputation: 13706

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");
                }
)

Upvotes: 3

Related Questions