I am attempting to suppress the flow of the execution context across asynchronous threads. I've written below code, but it throws an error -

InvalidOperationException: AsyncFlowControl object must be used on the thread where it was created.
System.Threading.AsyncFlowControl.Undo()
Web1.Controllers.ValuesController+<Get>d__0.MoveNext() in ValuesController.cs
+
                throw;
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

The error is not thrown when I debug through the code. It only occurs when I dont debug.

Sample code:

[HttpGet]
public async Task<IActionResult> Get()
{
    try
    {
        using (ExecutionContext.SuppressFlow())
        {
            await Switch.Instance.SwitchOn();
        }
    }
    catch (Exception ex)
    {
        var x = ex.Message;
        throw;
    }
    return Ok("Done!");
}

Am I going about it the wrong way?

1

There are 1 best solutions below

0
Stephen Cleary On

I am attempting to suppress the flow of the execution context across asynchronous threads.

Just have to ask: Why?

I've written below code, but it throws an error

This errors happens when you restore execution context flow on a different thread that you suspended it on.

To fix this error, just don't use await within the using block:

Task task;
using (ExecutionContext.SuppressFlow())
  task = Switch.Instance.SwitchOn();
await task;

By keeping the code in the using synchronous, you are ensuring you stay on the same thread.