我正在使用 NUnit 在 WPF 3.5 应用程序中测试 View 模型,我正在使用 BackgroundWorker
类来执行异步命令。单元测试在 NUnit 运行器或 ReSharper 运行器上运行良好但在 TeamCity 5.1 服务器上失败。
它是如何实现的:
我正在使用名为 IsBusy
的 ViewModel
属性,并在 BackgroundWorker.RunWorkerCompleted
事件中将其设置为 false。在我的测试中,我使用这种方法等待 BackgroundWorker 完成:
protected void WaitForBackgroundOperation(ViewModel viewModel)
{
Console.WriteLine("WaitForBackgroundOperation 1");
int count = 0;
while (viewModel.IsBusy)
{
Console.WriteLine("WaitForBackgroundOperation 2");
RunBackgroundWorker();
Console.WriteLine("WaitForBackgroundOperation 3");
if (count++ >= 100)
{
Assert.Fail("Background operation too long");
}
Thread.Sleep(1000);
Console.WriteLine("WaitForBackgroundOperation 4");
}
}
private static void RunBackgroundWorker()
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
System.Windows.Forms.Application.DoEvents();
}
好吧,有时它可以工作,有时它会挂起构建。我想是 Application.DoEvents()
但我不知道为什么...
编辑:我在日志中添加了一些痕迹(见上面的代码):
WaitForBackgroundOperation 1
WaitForBackgroundOperation 2
WaitForBackgroundOperation 2
WaitForBackgroundOperation 2
...
这怎么可能?!
最佳答案
您正在启动一堆后台任务,每秒一个。将 Run BackgroundWorker 移动到循环上方。
protected void WaitForBackgroundOperation(ViewModel viewModel)
{
Console.WriteLine("WaitForBackgroundOperation 1");
RunBackgroundWorker();
Thread.Sleep(100); // wait for thread to set isBusy, may not be needed
int count = 0;
while (viewModel.IsBusy)
{
Console.WriteLine("WaitForBackgroundOperation 2");
if (count++ >= 100)
{
Assert.Fail("Background operation too long");
}
Thread.Sleep(1000);
Console.WriteLine("WaitForBackgroundOperation 3");
}
}
private static void RunBackgroundWorker()
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
}
不需要 DoEvents。
关于c# - BackgroundWorker 不与 TeamCity NUnit runner 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2736032/