开发者

Closures and BackgroundWorker Event Handlers

开发者 https://www.devze.com 2023-04-05 00:31 出处:网络
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

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), i.e. 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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号