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   12 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   Genial fill someone in on and this post helped me alot in my college assignement. Gratefulness you on your information.
# posted by Anonymous Anonymous @ 9:30 AM   Do You interesting of [b]Female use of Viagra[/b]? You can find below...
[size=10]>>>[url=http://listita.info/go.php?sid=1][b]Female use of Viagra[/b][/url]<<<[/size]

[URL=http://imgwebsearch.com/30269/link/buy%20viagra/1_valentine3.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/1_valentine3.png[/IMG][/URL]
[URL=http://imgwebsearch.com/30269/link/buy%20viagra/3_headsex1.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/3_headsex1.png[/IMG][/URL]
[b]Bonus Policy[/b]
Order 3 or more products and get free Regular Airmail shipping!
Free Regular Airmail shipping for orders starting with $200.00!

Free insurance (guaranteed reshipment if delivery failed) for orders starting with $300.00!
[b]Description[/b]

Generic Viagra (sildenafil citrate; brand names include: Aphrodil / Edegra / Erasmo / Penegra / Revatio / Supra / Zwagra) is an effective treatment for erectile dysfunction regardless of the cause or duration of the problem or the age of the patient.
Sildenafil Citrate is the active ingredient used to treat erectile dysfunction (impotence) in men. It can help men who have erectile dysfunction get and sustain an erection when they are sexually excited.
Generic Viagra is manufactured in accordance with World Health Organization standards and guidelines (WHO-GMP). Also [url=http://twitter.com/jetlyca]q Buy Viagra Online[/url] you can find on our sites.
Generic [url=http://viagra.olistupa.ru]Viagra Super Active[/url] is made with thorough reverse engineering for the sildenafil citrate molecule - a totally different process of making sildenafil and its reaction. That is why it takes effect in 15 minutes compared to other drugs which take 30-40 minutes to take effect.
[b]viagra medication for erection
subaction showcomments viagra optional online
viagra no prescription
Philippines Viagra
viagras effects on woman
viagra levitra increase pleasure
coleman 2000 viagra elite
[/b]
Even in the most sexually liberated and self-satisfied of nations, many people still yearn to burn more, to feel ready for bedding no matter what the clock says and to desire their partner of 23 years as much as they did when their love was brand new.
The market is saturated with books on how to revive a flagging libido or spice up monotonous sex, and sex therapists say “lack of desire” is one of the most common complaints they hear from patients, particularly women.
# posted by Anonymous Anonymous @ 12:38 PM   Post a Comment

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