task.Wait抛出异常

时间:2010-12-08 05:24:48

标签: c# unit-testing parallel-processing task-parallel-library async-await

很大程度上作为这个问题的后续问题test driven asynch tasks我已经提出了一些代码,如果我没有等待任务就会有效,但如果我这样做就会失败。

任何人都可以解释原因吗?

例外:

当代码点击Stephen Cleary在他的博客here上编写的实用程序类的构造函数时,我收到此错误

public ProgressReporter()
{
    _scheduler = TaskScheduler.FromCurrentSynchronizationContext();
}

Test 'Smack.Core.Presentation.Tests.Threading.ProgressReporterTests.OnSuccessFullComplete_ExpectedResultIsReturned_JustWait' failed:
System.AggregateException : One or more errors occurred.
----> System.InvalidOperationException : The current SynchronizationContext may not be used as a TaskScheduler.
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
Threading\ProgressReporterTests.cs(142,0): at Smack.Core.Presentation.Tests.Threading.ProgressReporterTests.OnSuccessFullComplete_ExpectedResultIsReturned_JustWait()
--InvalidOperationException
at System.Threading.Tasks.SynchronizationContextTaskScheduler..ctor()
at System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext()
Threading\ProgressReporter.cs(24,0): at Smack.Core.Lib.Threading.ProgressReporter..ctor()
Threading\ProgressReporterTests.cs(52,0): at Smack.Core.Presentation.Tests.Threading.ProgressReporterTests._startBackgroundTask(Boolean causeError)
Threading\ProgressReporterTests.cs(141,0): at Smack.Core.Presentation.Tests.Threading.ProgressReporterTests.<OnSuccessFullComplete_ExpectedResultIsReturned_JustWait>b__a()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()

测试(NUnit w / TestDriven.Net亚军):

private class MockSynchContext : SynchronizationContext{}

[Test]
public void OnSuccessFullComplete_ExpectedResultIsReturned_Wait()
{
    var mc = new MockSynchContext();
    SynchronizationContext.SetSynchronizationContext(mc);
    Assert.That(SynchronizationContext.Current, Is.EqualTo(mc));
    Assert.DoesNotThrow(() => TaskScheduler.FromCurrentSynchronizationContext());
    var task = Task.Factory.StartNew(() => _startBackgroundTask(false));
    task.Wait(2000);
    _actualResult = 42;
}

SuT:

private void _startBackgroundTask(bool causeError)
{
    _cancellationTokenSource = new CancellationTokenSource();
    var cancellationToken = _cancellationTokenSource.Token;
    _progressReporter = new ProgressReporter();
    var task = Task.Factory.StartNew(() =>
            {
                for (var i = 0; i != 100; ++i) {
                    // Check for cancellation 
                    cancellationToken.ThrowIfCancellationRequested();

                    Thread.Sleep(30); // Do some work. 

                    // Report progress of the work. 
                    _progressReporter.ReportProgress(
                        () =>
                            {
                                // Note: code passed to "ReportProgress" can access UI elements freely. 
                                _currentProgress = i;
                            });
                }

                // After all that work, cause the error if requested.
                if (causeError) {
                    throw new InvalidOperationException("Oops...");
                }


                // The answer, at last! 
                return 42;
            },
        cancellationToken);

    // ProgressReporter can be used to report successful completion,
    //  cancelation, or failure to the UI thread. 
    _progressReporter.RegisterContinuation(task, () =>
    {
        // Update UI to reflect completion.
        _currentProgress = 100;

        // Display results.
        if (task.Exception != null)
            _actualErrorMessage = task.Exception.ToString();
        else if (task.IsCanceled)
            _wasCancelled = true;
        else 
            _actualResult = task.Result;

        // Reset UI.
        _whenCompleted();
    });
}

要明确:如果我注释掉task.Wait,该测试实际上是成功的。那是为什么?

加分:

我知道这在技术上是另一个问题,但重复所有这些似乎是一种耻辱,所以:

为什么我的MockSynchContext在我的测试中没有在TaskScheduler.FromCurrentSynchronizationContext()上抛出异常,但是在第二个任务中呢?更重要的是,有没有办法传递上下文,以便我可以正确地进行测试?

1 个答案:

答案 0 :(得分:8)

  

“如果我评论出任务。等等,那个测试确实成功了。为什么会这样?”

在实际检查任务之前,任务不会报告任务本身发生的异常(通过“等待”,“值”,“处理”等)。然后它重新抛出异常。在真实的应用程序中,GC最终会到达任务并导致您的应用程序崩溃。