'How to add a delay when returning an infinite stream from Asp.net WebApi controller?
I'm trying to add a half a second delay to an infinite stream of data which I send through an Asp.net Core (.net 5 ) webapi method and I can't figure out how to make the code NOT deadlock.
Background
I'm creating a quick and dirty method to simulate receiving data from a webservice which return an infinite stream of string, with each line terminated with a new line character.
I'm able to send a never ending stream of data with this code below just fine, however I'd like to add a 0.5 second delay between each line.
The problem I have is of deadlock I believe.
await Task.Delay(500); causes my server to not return anything after Message number 0.
If I remove that line, it works fine and my test console app starts to receive the infinite stream of text as expected.
Asp.net core webAPI (.net 5) serverside code which only works if I don't use Task.Delay (note that I have tried adding ConfigureAwait(false) with no effect, but then this is asp.net core without a sync context anyway)
[HttpGet]
public async Task Get()
{
var outputStream = this.Response.Body;
int i = 0;
while (true)
{
await Task.Delay(500);
byte[] bytes = Encoding.ASCII.GetBytes("Message number " + i.ToString() + Environment.NewLine);
await outputStream.WriteAsync(bytes);
i++;
}
}
Here is how I'm consuming the response in another test .net core console app(.net 5)
string dataReceived = "";
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
dataReceived = reader.ReadLine();
if (dataReceived.Length <= 1) continue;
//here, do something with the data.
//it ONLY reaches this line if I don't use task.delay on the server side
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
