Skip to content

Should I manually flush HttpResponse.BodyWriter? Docs seems to contradict actual practices in MVC #62464

Answered by davidfowl
scharnyw asked this question in General
Discussion options

You must be logged in to vote

Newtonsoft.Json isn’t async and doesn’t use the newer async APIs. So when it flushes buffered bytes to the underlying stream, it blocks—tying up a thread pool thread.

SystemTextJsonOutputFormatter, on the other hand, calls SerializeAsync, which is key here. System.Text.Json writes to the underlying writer as it serializes the object, and because it’s async, it doesn’t block a thread.

Both cases buffer and flush automatically based on internal heuristics—things like how StreamWriter or JsonSerializer are configured.

I have an application that writes large JSON responses manually using Utf8JsonWriter for performance. It used to write to HttpResponse.Body (a Stream), but now I’m switching to

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@scharnyw
Comment options

Answer selected by scharnyw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants