2016-02-20 21 views
6

場合でも、私はこのコードでUWP WinRTの上JSONストリームを消費しています完了している:DataReader.loadAsyncがunconsumedBufferLengthが0

ここ
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であってもCPU負荷が発生してもreader.loadAsyncが完了します。これはAPIのバグですか?が0より大きい場合にのみloadAsyncが完了できるようにこの動作を防止できますか?

PS:ここでは、純粋なJSとREPROです:https://github.com/SaschaNaz/InputStreamOptionsBugRepro

答えて

1

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

ほとんどが、それはまた、ストリームの終わりに完了likey。その場合、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) 

+0

ああストリームはloadAsync 'ように、切断されたときに、ここでは' canceled'変数がtrueになります'その場合は呼び出されません。 –

+0

@ KagamiSaschaRosylightキャンセルされた変数のロジックを表示 – basarat

+0

さて、私はもっと多くの行を追加しました。 'loadAsync'は、切断されたストリームでエラーを送出します。' WinRTError:オブジェクトが閉じられました.''切断後に 'loadAsync'が呼び出されないことを確認できます。 –