Define a RunWorkerCompleted flashlight with an anonymous method?

Hope I used the correct term

What I'm aiming for is something like this (I understand this doesn't work):

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

An important part is the RunWorkerCompletedEventHandler, defined within the scope of the original call and to those who have access to the variables of the caller.

Is it possible? Will this generate possible race conditions on someBool?

+2
multithreading c # lambda
source share
2 answers

In your example, this does not work, since the full 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"); } ) 
+3
source share

It all depends on what else bool is using.

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

However, I feel that you should use synchronization like Monitor , perhaps with a pulse, etc., or a shutter like ManualResetEvent .

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

0
source share

All Articles