我在实现BackgroundWorker类时遇到了一个奇怪的问题。它在我的程序中运行一些测试(对于一些对这个问题不重要的硬件)。这是我为BackgroundWorker编写的代码:
public AllTests(MainMenu p)
{
InitializeComponent();
WindowStartupLocation = WindowStartupLocation.CenterScreen;
this.parent = p;
generateCaseLabels(tc.getTCs());
var testThread = new BackgroundWorker();
// Tell the testthread what to do
testThread.DoWork += (sender, args) =>
{
List<BaseTestCase> cases = tc.getTCs();
foreach ( BaseTestCase test in cases )
{
test.execute();
while (!test.Done) { Thread.Sleep(500); }
if (test.Passed)
{
passed.Add(test);
}
else
{
failed.Add(test);
}
}
};
// Start the TestReport after the testing is completed
testThread.RunWorkerCompleted += (sender, args) =>
{
TestReport newWindow = new TestReport(parent, passed, failed);
testThread.CancelAsync(); // reset the testThread (?)
log.append(this, "--- DONE TESTING --------------------");
newWindow.Show();
this.Close();
};
// Start the testthread
testThread.WorkerSupportsCancellation = true;
testThread.RunWorkerAsync();
}
该代码发生的奇怪之处在于,当第一次启动时,它工作得很好,但当再次导航到此AllTests
窗口时,TestReport
窗口会立即打开,表明testThread.RunworkerCompleted
会立即被调用。所以我的问题是:有人知道重置BackgroundWorker或其他什么聪明的方法吗,或者对这种奇怪的行为有答案吗?
顺便说一句,以下是我如何调用AllTests窗口:
private void startTests(object sender, RoutedEventArgs e)
{
log.append(this, "--- STARTING ALL TESTS --------------------");
AllTests newWindow = new AllTests(parent);
newWindow.Show(); this.Close();
}
谢谢你的帮助!罗伯特。
PS如果我有拼写错误或问题不够清楚;请原谅,英语不是我的母语,这是我在StackOverflow上的第一篇帖子!谢谢
这取决于如何关闭"AllTests"窗口。例如,在这个简化的测试中,它工作并每次调用后台工作程序:
// simple main form with a button to open the 2nd form
public partial class MainWindow : Window
{
public MainWindow() { InitializeComponent(); }
private void Button_Click(object sender, RoutedEventArgs e) { new PopupWindow().Show(); }
}
// 2nd popup window constructor (hence background worker) fires after form is closed and re-opened from the main form
public partial class PopupWindow : Window
{
public PopupWindow()
{
InitializeComponent();
WindowStartupLocation = WindowStartupLocation.CenterScreen;
var testThread = new BackgroundWorker();
{
testThread.DoWork += (sender, args) => { MessageBox.Show("doWork running"); };
testThread.RunWorkerCompleted += (sender, args) => { MessageBox.Show("doWork completed"); };
testThread.WorkerSupportsCancellation = true;
testThread.RunWorkerAsync();
}
}
}