Architect or Cobbler?
Good code starts with good design

How to use BackgroundWorker properly ;-)

Saturday, December 23, 2006

Well, I've been looking at the problem a little more carefully, and it is definitely a race condition, however you can avoid it quite simply.  First a bit of code that demonstrates the problem more fully.   

        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1 = new BackgroundWorker();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.DoWork += DoWork;
            backgroundWorker1.ProgressChanged += ProgressChanged;
            backgroundWorker1.RunWorkerAsync();
        }
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            // You need to call this in an invoke as you 
            // are writing back to the UI thread
            BeginInvoke(new MethodInvoker(WriteHelloToTextBox));
        }

        private void WriteHelloToTextBox()
        {
            textBox1.Text = "Hello";
            Thread.Sleep(100);
            backgroundWorker1.ReportProgress(100);
            
        }

        private void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }
 

The problem stems from the fact that DoWork is run in a separate thread, so if you have to write to the GUI then you have to marshal it via Invoke.  So naturally in my eagerness to improve performance I use BeginInvoke, which simply spawns a thread and then continues.  The spawned thread then sleeps for a bit (just to make the race condition more apparent - even without the sleep this code will occasionally fail) writes to a textbox and then reports progress.  By the time the ReportProgress call is marshaled to the right thread, the thread has completed as DoWork will have finished.  The solution is simple, never use BeginInvoke (or indeed spawning a new thread by any other means) from the DoWork handler, so to fix the code above, just change BeginInvoke to Invoke - it works every time now, and is certainly better than my cludgy sleep I was using earlier  :-)


# posted by James @ 6:14 PM   10 comments Comments: I found this site using [url=http://google.com]google.com[/url] And i want to thank you for your work. You have done really very good site. Great work, great site! Thank you!

Sorry for offtopic
# posted by Anonymous Anonymous @ 1:19 AM   Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!
# posted by Anonymous Anonymous @ 12:34 AM   This theme is simply matchless :), very much it is pleasant to me)))
# posted by Anonymous Anonymous @ 10:43 AM   That’s Too nice, when it comes in india hope it can make a Rocking place for youngster.. hope that come true.
# posted by Anonymous Anonymous @ 4:25 AM   It is very valuable piece
# posted by Anonymous Anonymous @ 12:32 PM   It is remarkable, very amusing phrase

There is a site on a theme interesting you. Hot Health
# posted by Anonymous Anonymous @ 4:04 PM   alappuzha delightfully holton monika vehicles barrage purposesee refrain crucial selections prospectus
servimundos melifermuly
# posted by Anonymous Anonymous @ 8:09 AM   locates davie jsyeast carlos garran reintroduces srivastavaen recruiters punjabi instructors gksxh
servimundos melifermuly
# posted by Anonymous Anonymous @ 3:06 PM   archaeometry an positives and negatives of tl dating [url=http://loveepicentre.com/]ads dating exotic personal service[/url] online adult dating http://loveepicentre.com/ ireland dating
# posted by Anonymous Anonymous @ 7:59 PM   auto audio [url=http://www.cardvdplanet.com/ultra-double-din-6-2-inch-lcd-car-dvd-with--discount-price5.html]discount auto dvd player[/url] chrysler car audio http://www.cardvdplanet.com/9-inch-portable-dvd-player-support-tv--discount-price100.html best auto dvd player
auto audio las vegas [url=http://www.cardvdplanet.com/new-car-dvd-player-online-store6.html]beststuff fuel car dvd ipod vacation[/url] auto audio wiring kits http://www.cardvdplanet.com/shadow-chrome-stylish-touch-screen-car-dvd-with--discount-price7.html car audio toyota
cathedral city auto audio [url=http://www.cardvdplanet.com/car-radio-with-usb-sd-mmc-card-discount-price115.html]beststuff fuel car dvd ipod vacation houseboat lake powell home[/url] install auto dvd player http://www.cardvdplanet.com/1-din-large-screen-online-store5.html jvc auto audio manuals
# posted by Anonymous Anonymous @ 1:48 AM   Post a Comment

<< Main blog page
This page is powered by Blogger. Isn't yours?