I believe I have a race condition below. I am manually constructing an HttpResponseMessage
with JSON output to stream asynchronously. The issue seems to be with the counter (i). I want to add a comma before any element after the first write from the list.
At the beginning of the list, sometimes the the first couple of records following the first write(i've seen up to 3) will not have the preceeding comma. The number is inconsistent and sometimes works as expected. I did not see it on my local machine, but in deployed environments with beefier hardware it's present.
var LastUpdate = JsonConvert.SerializeObject(dt);
var pre = $"{{ \"LastUpdate\": {LastUpdate}, \"List\":[";
var post = "]}";
HttpResponseMessage response = Request.CreateResponse();
response.Content = new PushStreamContent(
async (stream, http, context) =>
{
try
{
int i = 0;
var buffer = Encoding.UTF8.GetBytes(pre);
await stream.WriteAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
var query = getQuery(id);
await query
.ForEachAsync(async entity =>
{
var student = MapRecord(entity);
if (student != null)
{
var json = JsonConvert.SerializeObject(student);
buffer = Encoding.UTF8.GetBytes(((i > 0) ? ", " : "") + json);
await stream.WriteAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
i++;
}
}, cancellationToken).ConfigureAwait(false);
buffer = Encoding.UTF8.GetBytes(post);
await stream.WriteAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
}