Search code examples
c#asp.net-coreservicestackasp.net-core-6.0servicestack-text

Async ServiceStack.Text


From what I can tell ServiceStack.Text does not have async stream/writer support for serialization. In asp.net core 6 synchronous IO is disabled by default so if you want to use ServiceStack.Text as your JsonOutputFormatter your choices are

  1. enable synchronous IO AllowSynchronousIO = true
  2. serialize to a string then write async to the response stream
var json = JsonSerializer.SerializeToString(context.Object);
await responseStream.WriteAsync(Encoding.UTF8.GetBytes(json), httpContext.RequestAborted);
await responseStream.FlushAsync(httpContext.RequestAborted);

Which of the above two options is better?

Is there a third option?


Solution

  • Writing to a string then writing that asynchronously to a Stream is going to be more portable given it doesn't need to rely on external AllowSynchronousIO being enabled.

    Although you can make this more efficient by using a BufferPool and Memory<byte> for the UTF8 conversion, e.g:

    var buf = BufferPool.GetBuffer(Encoding.UTF8.GetByteCount(json));
    Memory<byte> bytes = buf;
    await stream.WriteAsync(bytes[..Encoding.UTF8.GetBytes(json, bytes.Span)]);
    BufferPool.ReleaseBufferToPool(ref buf);