繁体   English   中英

BackgroundWorker不与TeamCity NUnit运行器一起使用

[英]BackgroundWorker not working with TeamCity NUnit runner

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

如何实施:

我正在使用一个名为IsBusyViewModel属性,并在BackgroundWorker.RunWorkerCompleted事件IsBusy其设置为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
...

这怎么可能 ?!

您正在启动一堆后台任务,每秒执行一次。 将RunBackgroundWorker移到循环上方。

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM