Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3596706
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T20:01:24+00:00 2026-05-18T20:01:24+00:00

Largely as a follow-up to this question test driven asynch tasks I have come

  • 0

Largely as a follow-up to this question test driven asynch tasks I have come up with some code that works if I don’t have the task wait, but fails if I do.

Can anyone explain why?

Exception:

I get this error when the code hits the constructor of a utility class written by Stephen Cleary on his blog 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()

The test (NUnit w/ TestDriven.Net runner):

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;
}

The 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();
    });
}

Just to be clear: If I comment out task.Wait, that test actually succeeds. Why is that?

Extra points:

I know this is technically another question but it seems a shame to repeat all of this, so:

Why did my MockSynchContext not throw an exception on TaskScheduler.FromCurrentSynchronizationContext() in my test but did in the second task? More importantly, is there a way to pass the context along so I can do the test properly?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T20:01:25+00:00Added an answer on May 18, 2026 at 8:01 pm

    “If I comment out task.Wait, that test actually succeeds. Why is that?”

    Task doesn’t report exceptions that happen in the Task itself until you actually examine the Task (either by ‘Wait’, ‘Value’, ‘Dispose’, etc). It then rethrows the exception. In a real app, eventually the GC would reach the Task and cause your app to crash.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Largely as a follow-up to this question test driven asynch tasks I have come
I have read some tips that multithread implementation largely depends on the target OS
I have a question. In the framework, that was largely written before the generics
Suppose I have some kind of factory function which creates objects that are largely
I know this is largely an opinion, but I'm interested if you have one
I'm coming largely from a c++ background, but I think this question applies to
I am running simulation code that is largely bound by CPU speed. I am
We currently have an application that depends largely on stored procedures. There is a
I have a toolbar developed under older versions of Windows that is largely cut
I'm finding that the code that I write in my controllers is largely repetitive

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.