Synchronous operations are disallowed
By FoxLearn 3/4/2025 10:03:34 AM 32
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:
- Use asynchronous I/O methods (Recommended)
- 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.
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
- Only one parameter per action may be bound from body in ASP.NET Core
- The request matched multiple endpoints in ASP.NET Core
- How to Create a custom model validation attribute in ASP.NET Core
- How to disable ModelStateInvalidFilter in ASP.NET Core
- How to fix LoginPath not working in ASP.NET Core
- Async SSE endpoint in ASP.NET Core