|
Architect or Cobbler?
Good code starts with good design |
|
about me
links
Blogs I follow
recent posts
archives
feeds |
How to use BackgroundWorker properly ;-)Saturday, December 23, 2006Well, 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 Sorry for offtopic # posted by @ 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 @ 12:34 AM Post a Comment << Main blog page |
|
|
|