简体   繁体   中英

Closures and BackgroundWorker Event Handlers

I have a simple BackgroundWorker defined that uses closures for its DoWork and RunWorkerCompleted event handlers, which set and check a boolean value, respectively. In simplified form, the code (C# in .NET 3.5) looks like this:

    public void SomeMethod()
    {
         BackgroundWorker worker = new BackgroundWorker();

         bool result = false;
         worker.DoWork += new DoWorkEventHandler(
             (sender, e) =>
             {
                 result = LengthyOperation(); 
             });

         worker.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(
             (sender, e) => 
             {
                 AppendRunLog("Result: " + (result ? "PASS" : "FAIL"));
             });

         worker.RunWorkerAsync();
     }

SomeMethod is called from a WPF button handler on the main UI thread.

Usually this works just fine, but every so often I get a report that the operation has failed when it should have passed (according to logs generated inside LengthyOperation), ie the boolean result gets logged as false in the Completed handler when the operation should have returned true in the DoWork handler.

I scoured and tested the heck out of the code inside LengthyOperation to make sure I didn't have some subtle bug inside it, and I am fairly confident it is clean. I have not been able to reproduce it in my development environment.

Do I have a race condition in how I am setting and reading the result value? I would expect that the assignment operation would have completed in DoWork before the Completed event is fired.

Looks like it should be fine to me, assuming that the BackgroundWorker infrastructure makes sure there are appropriate memory barriers.

Are you sure you don't just have two concurrent operations, and you're seeing two sets of logs at the same time?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM