Working on UWP WinRT, I'm dealing with JSON stream consumption using the following code:
async function connect() {
let stream: MSStream;
return new CancellableContext<void>(
async (context) => {
stream = await context.queue(() => getStreamByXHR()); // returns ms-stream object
await consumeStream(stream);
},
{
revert: () => {
stream.msClose();
}
}
).feed();
}
async function consumeStream(stream: MSStream) {
return new CancellableContext<void>(async (context) => {
const input = stream.msDetachStream() as Windows.Storage.Streams.IInputStream;
const reader = new Windows.Storage.Streams.DataReader(input);
reader.inputStreamOptions = Windows.Storage.Streams.InputStreamOptions.partial;
while (!context.canceled) {
const content = await consumeString(1000);
}
async function consumeString(count: number) {
await reader.loadAsync(count);
return reader.readString(reader.unconsumedBufferLength);
}
}).feed();
}
In this scenario, the InputStreamOptions.partial
documentation mentions:
The asynchronous read operation completes when one or more bytes is available.
However, the issue arises when reader.loadAsync
completes even if reader.unconsumedBufferLength
is 0, causing high CPU load. Is there a way to prevent this so that loadAsync
only completes when unconsumedBufferLength
is greater than 0? Or is this behavior intended?
PS: For additional information, refer to this repro in pure JS: https://github.com/SaschaNaz/InputStreamOptionsBugRepro