System.ComponentModel.BackgroundWorker never invokes ProgressChanged
I recently rewrote my Windows Forms application to use BackgroundWorker instances instead of using manually created "worker threads". After checkin I noticed some tests started to fail. After some debugging I can demonstate my problems by showing you the following 2 tests:
[Test]
public void Test_A()
{
bool progressChanged = false;
var worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += (s, e) => worker.ReportProgress(0, null);
worker.ProgressChanged += (s, e) => progressChanged = true;
worker.RunWorkerAsync();
Thread.Sleep(100);
progressChanged.ShouldBeTrue();
}
[Test]
public void Test_B()
{
//Creation of o form component causes (?) this test to fail, even do I dispose it
var view = new Form();
view.Dispose();
bool progressChanged = false;
var worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += (s, e) => worker.ReportProgress(0, null);
worker.ProgressChanged += (s, e) => progressChanged = true;
worker.RunWorkerAsync();
Threa开发者_运维技巧d.Sleep(100);
progressChanged.ShouldBeTrue();
}
Test_A success while Test_B fails. This is regardless if I sleep 100 ms or 100 minutes. Why?? My production code seem to work though, but it is annoying not being able to have a regression test suite that works (I have other test creating Forms components and these tests must be executed BEFORE my test using BackgroundWorker) The next step would be to examine the source code of BackgroundWorker, but before I do that I thought I`d check for help here.
Regards Michael
Add
WindowsFormsSynchronizationContext.AutoInstall = false;
In Test_B() before anything else. The BackgroundWorker, wich is very UI (ie: Winforms) oriented, is wild guessing how to sync things, but not like you want. Have a look here for some explanation (especially from Scott Berry): WindowsFormsSynchronizationContext
精彩评论