gpt4 book ai didi

javascript - 即使 unconsumedBufferLength 为 0,DataReader.loadAsync 也正在完成

转载 作者:数据小太阳 更新时间:2023-10-29 05:35:26 31 4
gpt4 key购买 nike

我使用以下代码在 UWP WinRT 上使用 JSON 流:

async function connect() {
let stream: MSStream;
return new CancellableContext<void>(
async (context) => {
// this will be called immediately
stream = await context.queue(() => getStreamByXHR()); // returns ms-stream object
await consumeStream(stream);
},
{
revert: () => {
// this will be called when user cancels the task
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);
// ... some more codes
}

async function consumeString(count: number) {
await reader.loadAsync(count); // will throw when the stream gets closed
return reader.readString(reader.unconsumedBufferLength);
}
}).feed();
}

这里是关于InputStreamOptions.partial的文档说:

The asynchronous read operation completes when one or more bytes is available.

但是,即使 reader.unconsumedBufferLength 为 0,reader.loadAsync 也会完成,这会增加 CPU 负载。这是 API 错误还是我可以阻止此行为,以便 loadAsync 仅在 unconsumedBufferLength 大于 0 时才能完成?

PS:这是一个纯JS的复现:https://github.com/SaschaNaz/InputStreamOptionsBugRepro

最佳答案

Is this an API bug or can I prevent this behavior so that loadAsync can complete only when unconsumedBufferLength is greater than 0

最有可能它也在流的末尾 完成。因此,在那种情况下,unconsumedBufferLength 将为零并且需要满足。

事实上 https://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.streams.datareader.aspx 的例子显示类似的东西(不可否认没有使用那个选项):

            // Once we have written the contents successfully we load the stream.
await dataReader.LoadAsync((uint)stream.Size);

var receivedStrings = "";

// Keep reading until we consume the complete stream.
while (dataReader.UnconsumedBufferLength > 0)

🌹

关于javascript - 即使 unconsumedBufferLength 为 0,DataReader.loadAsync 也正在完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35527614/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com