Synchronous operations are disallowed

By FoxLearn 3/4/2025 10:03:34 AM   32
When performing a synchronous I/O operation in ASP.NET Core (such as writing to a file), you may encounter the following exception:
System.InvalidOperationException: ‘Synchronous operations are disallowed. 
Call WriteAsync or set AllowSynchronousIO to true.

This happens because the AllowSynchronousIO setting is false by default in ASP.NET Core 3.0 and later.

Solution

Microsoft disabled synchronous I/O operations by default to prevent thread starvation and application hangs. You have two ways to resolve this issue:

  1. Use asynchronous I/O methods (Recommended)
  2. Enable AllowSynchronousIO (Short-term workaround)

Use Asynchronous I/O Methods (Recommended)

The best practice is to replace synchronous I/O calls with their asynchronous counterparts. For example, use WriteLineAsync() instead of WriteLine().

To fully support asynchronous execution, ensure that async/await is used throughout the call chain, starting from the API entry point.

Before: Using Synchronous I/O (Throws Exception)

[HttpGet]
[Route("messages/subscribe/{id}")]
public void Subscribe(string id)
{
    Response.ContentType = "text/event-stream";
    Response.StatusCode = 200;

    StreamWriter streamWriter = new StreamWriter(Response.Body);

    streamWriter.WriteLine($"{DateTime.Now} Hello subscriber");
    streamWriter.Flush();
}

After: Using Asynchronous I/O (Fixes the Issue)

[HttpGet]
[Route("messages/subscribe/{id}")]
public async Task Subscribe(string id)
{
    Response.ContentType = "text/event-stream";
    Response.StatusCode = 200;

    StreamWriter streamWriter = new StreamWriter(Response.Body);

    await streamWriter.WriteLineAsync($"{DateTime.Now} Hello subscriber");
    await streamWriter.FlushAsync();
}

By making these changes, the endpoint avoids the Synchronous operations are disallowed exception.

Enable AllowSynchronousIO (Temporary Fix)

If you need a quick fix without modifying existing code, you can re-enable synchronous I/O by setting AllowSynchronousIO = true.

For IIS:

builder.Services.Configure<IISServerOptions>(options =>
{
    options.AllowSynchronousIO = true;
});

For Kestrel:

builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.AllowSynchronousIO = true;
});

Noted:

  • This is a temporary workaround and not recommended for long-term use.
  • Before .NET 6, apply this setting inside Startup.ConfigureServices().

For a scalable and efficient solution, it's best to adopt asynchronous I/O methods instead of re-enabling synchronous operations.