Despite the unconsumedBufferLength being 0, DataReader.loadAsync is still being completed

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

Answer №1

Is there a way to address this issue with the API or can I take steps to ensure that loadAsync only completes when unconsumedBufferLength is greater than zero?

It seems like the completion also occurs at the end of stream. In that scenario, the unconsumedBufferLength will be zero and adjustments will need to be made for this situation.

In fact, a similar example is shown on https://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.streams.datareader.aspx, although not exactly using that option:

// Once the content has been successfully written, we proceed to load the stream.
await dataReader.LoadAsync((uint)stream.Size);

var receivedStrings = "";

// Continue reading until the entire stream is consumed.
while (dataReader.UnconsumedBufferLength > 0)

🌹

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve and bind data using onMounted in VueJS

Loading Data in Test.vue Component <template> <li v-for="item in masterCompany" v-bind:key="item.id"> {{ item.displayName }} </li> </template> <script> import Test from "../hooks/Test.hook" ...

Microsoft Edge browser incorrectly calculates range.endOffset value

This particular problem is specific to the Microsoft Edge browser. I am attempting to apply a CSS style to a selected word using Range API's, but I am encountering an issue with the range.endOffset functionality in Edge. Below is the code snippet I am ...

What is the best way to retrieve the latest files from a Heroku application?

Having recently migrated my Discord Bot to Heroku, I faced a challenge with retrieving an updated file essential for code updates. I attempted using both the Git clone command and the Heroku slugs:download command with no success in obtaining the necessar ...

Sort firebase information by chronological order based on timestamp

I'm currently working on sorting track IDs from firebase based on their timestamp (createdAt). The function is functioning correctly, but the ordering doesn't seem to work as expected. I'm not sure where the issue lies. Any assistance or sug ...

The "body" object cannot be accessed in a post request made from an Express router

I am currently utilizing Express router functions to manage some POST requests. Client.js let data = { endpoint: "Blah Blah"; }; return fetch('/api/get-preferences/', { method: 'POST', headers: { 'Content-Type': & ...

Tips for adapting the position of a floating div according to its height and environment

Important Note: The code below utilizes the rubuxa plugin for handling JS sortables. Javascript: function querySelector(expr){return document.querySelector(expr)} var container = querySelector('.ITEST'); var sortable = Sortable.create(container, ...

Ways to retrieve information from JSON

I am currently trying to access the values of an object that is within an array which is inside another object. The data is structured as follows: [{ "id": "99a4e6ef-68b0-4cdc-8f2f-d0337290a9be", "stock_name": "J ...

Uploading images in React JS by allowing users to paste images

Currently working on a chat application using React JS and I'm looking to enable image uploading when an image is pasted into the chatbox. How can I make this happen? Essentially, I am in need of: An event that will activate upon performing the "Pas ...

Error message encountered following the removal of an undesirable type from an array in Typescript

When working with TypeScript, I am facing an issue. I have an array defined as Array<string|undefined, and my goal is to filter out the undefined values from this array and assign the resulting array to a variable of type Array<string>. However, I ...

Is there a way to fix the error "The requested resource does not have the 'Access-Control-Allow-Origin' header" within Express using Firebase functions?

Trying to send an email through nodemailer using Firebase functions, but encountering errors. The data for the email will come from a form. Error message: Access to XMLHttpRequest at 'my-firebase-functions' from origin 'my-angular-web-app&a ...

Include a link to a JavaScript file within a dynamically created HTML page in a Delphi VCL application

I am currently developing a Delphi XE5 VCL Forms Application which includes a TIdHTTPServer on the main form. Within this server, there is a CommandGet procedure called IdHTTPServer: procedure TForm1.IdHTTPServerCommandGet(AContext: TIdContext; ARequest ...

Retrieve data from cookies that have been stored by the node server on the front end

I am currently utilizing the Node package 'cookie' to establish cookies from the backend as shown below: res.setHeader('Set-Cookie', cookie.serialize('token', token, { maxAge: 60 * 60 * 24 * 7 // 1 week ...

Resolve the Prototype_Pollution vulnerability detected by Checkmarx

When executing the code line window.location.search.substring(1) with the word 'substring(1)', an error related to Prototype_Pollution occurs. This error is caused by assigning external properties without proper validation, which can lead to obje ...

Resolving a persistent AngularJS 1 constant problem with Typescript

I'm currently developing an application using TypeScript and AngularJS 1, and I've encountered a problem while trying to create a constant and passing it to another class. The constant in question is as follows: module app{ export class A ...

The ExpressJS EJS issue arises when trying to access a property that is undefined

I'm new to NodeJS and seeking assistance. I am working on a website where users can promote their virtual conferences for others to see. I have set up a form with the POST method, where the data gets pushed into an array and then displayed in an EJS f ...

Can anyone suggest a more efficient method for validating checkbox selection in Angular?

I am working with an angular material stepper, where I need to validate user selections at each step before allowing them to proceed. The first step displays a list of 'deliveries' for the user to choose from, and I want to ensure that at least o ...

Iterate through all elements in Javascript/jQuery while excluding any nested children elements

Looking to retrieve all elements in the document: $("*").each(function(){ var el = $(this); }); I want to target only parent elements, excluding their children. For example: <div> <!--TARGET--> <div></div> <!--IGNORE--&g ...

What is the most efficient way to save a document in mongoose based on a specific user's

Is there a way to ensure that when saving a template, it is associated with the user id? I have added a reference to the templateSchema for the User. User.model.js var UserSchema = new mongoose.Schema({ _id: { type: String, required: true, index: {uniq ...

Searching for variables within files using Node.js and constructing an object from the results

Trying to figure out how to streamline this process. Here's the directory structure I'm working with: src/ modules/ clients/ i18n/ en-US.ts tasks/ i18n/ en-US.ts So, ea ...

Alter the class when $dirty occurs in Angular

I've recently started working with angular js and am attempting to incorporate animations into my login page. I have created a controller that will modify the class of the input field when clicked and when blurred. app.controller("con", function($sc ...