4

I had an REST API targeting AspNetCore 2.2 with an endpoint that allows download of some big json files. After migrating to AspNetCore 3.1 this code stopped working:

    try
    {
        HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
        HttpContext.Response.Headers.Add("Content-Type", "application/json");

        using (var bufferedOutput = new BufferedStream(HttpContext.Response.Body, bufferSize: 4 * 1024 * 1024))
        {
            await _downloadService.Download(_applicationId, bufferedOutput);
        }
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, ex.Message);                
    }

This is the download method, that created the json that I want to return on the HttpContext.Response.Body:

    public async Task Download(string applicationId, Stream output, CancellationToken cancellationToken = default(CancellationToken))
    {       
        using (var textWriter = new StreamWriter(output, Constants.Utf8))
        {
            using (var jsonWriter = new JsonTextWriter(textWriter))
            {
                jsonWriter.Formatting = Formatting.None;
                await jsonWriter.WriteStartArrayAsync(cancellationToken);

                //write json...
                await jsonWriter.WritePropertyNameAsync("Status", cancellationToken);
                await jsonWriter.WriteValueAsync(someStatus, cancellationToken); 

                await jsonWriter.WriteEndArrayAsync(cancellationToken);
            }
        }
    }

Now I get this exception: "Synchronous operations are disallowed in ASP.NET Core 3.0" How can I change this code to work without using AllowSynchronousIO = true;

1
  • Could it be one of the Streams requires a FlushAsync before the using block ends? That's one of the hidden ones since a using statement calls Dispose(), which is not async. C# 8 does bring the async using version for objects that support IAsyncDIsposable.
    – juunas
    Commented Apr 2, 2020 at 5:38

4 Answers 4

6

AllowSynchronousIO option is disabled by default from .Net core 3.0.0-preview3 in (Kestrel, HttpSys, IIS in-process, TestServer) because these APIs are source of thread starvation and application hangs.

The option can be overridden on a per request for a temporary migration :

var allowSynchronousIoOption = HttpContext.Features.Get<IHttpBodyControlFeature>();
if (allowSynchronousIoOption != null)
{
    allowSynchronousIoOption.AllowSynchronousIO = true;
}

You can find more info and follow the ASP.NET Core Issue Tracker : AllowSynchronousIO disabled in all servers

2
  • Yes, this is what I have used for the endpoint where I need it, but I wanted to see if I can manage without it; replacing with BufferedReadStream or something
    – Angela
    Commented Apr 2, 2020 at 6:32
  • Just return return File(byteFile, "application/json", enableRangeProcessing:true);, the enableRangeProcessing helps client to resume file downloads.
    – XAMT
    Commented Apr 2, 2020 at 7:22
5

By calling FlushAsync and DisposeAsync before exiting using clause, you can stop synchronous operations that happen during writer dispositions. BufferedStream seems to have the synchronous write issue, how about control the buffer size in StreamWriter.

using (var streamWriter = new StreamWriter(context.Response.Body, Encoding.UTF8, 1024))
using (var jsonWriter = new JsonTextWriter(streamWriter))
{
    jsonWriter.Formatting = Formatting.None;
    await jsonWriter.WriteStartObjectAsync();
    await jsonWriter.WritePropertyNameAsync("test");
    await jsonWriter.WriteValueAsync("value " + new string('a', 1024 * 65));
    await jsonWriter.WriteEndObjectAsync();

    await jsonWriter.FlushAsync();
    await streamWriter.FlushAsync();
    await streamWriter.DisposeAsync();
}

In this way, you can make your code work with a small change without AllowSynchronousIO = true

2

I was able to solve this problem by using

Response.BodyWriter.AsStream()

instead of

Response.Body
0

Synchronous Dispose methods can contain synchronous IO methods (e.g. calling Flush) which would result in the error you're seeing. Where available (when the class implements IAsyncDisposable), you should instead call await using, which should avoid the use of any synchronous IO when disposing. So for your example, you would want to use:

await using (var textWriter = new StreamWriter(output, Constants.Utf8))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.