c# - BackgroundWorker 不与 TeamCity NUnit runner 一起工作

标签 c# .net nunit teamcity backgroundworker

我正在使用 NUnit 在 WPF 3.5 应用程序中测试 View 模型,我正在使用 BackgroundWorker 类来执行异步命令。单元测试在 NUnit 运行器或 ReSharper 运行器上运行良好但在 TeamCity 5.1 服务器上失败。

它是如何实现的:

我正在使用名为 IsBusyViewModel 属性,并在 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/

相关文章:

c# - 如何组织单元测试而不让重构成为噩梦?

c# - 将 sql 语句的结果存储到字符串中,并将其与列表框中选择的项目进行比较

c# - 使用 .NET Core 3.1 和 HttpContext 的客户端 IP 地址错误

.net - 如何根据 CPU 架构使用正确的非托管 DLL 文件? (32/64 位)

c# - 在 .net 4.0 版本上找不到 System.Web 程序集

c# - 使用 NUnit 作为可部署的测试套件

Nunit 使用的 XML 文件的 XSD

c# - 为什么 C# 发布版本包含调试信息

c# - 是否可以为 asp.net web 表单应用程序编写 action-filter 属性?

c# - 什么是最高效的,为什么?