11using System ;
22using System . Buffers ;
3+ using System . Diagnostics ;
34using System . IO ;
45using System . IO . Pipelines ;
56using System . Threading ;
@@ -20,28 +21,37 @@ public IBufferWriter<byte> Output
2021 }
2122 }
2223
23- private void CreateOutputPipe ( )
24+ private Task _writeComplete = Task . CompletedTask ;
25+
26+ private void InitOutput ( Stream ? stream )
2427 {
25- if ( _ioStream is not { } stream ) return ;
28+ if ( stream is null ) return ;
29+ _ioStream = stream ;
2630 var pipe = new Pipe ( ) ;
2731 _output = pipe . Writer ;
28- _ = Task . Run ( ( ) => CopyOutputAsync ( this , pipe . Reader , stream ) ) ;
32+ _writeComplete = Task . Run ( ( ) => CopyOutputAsync ( this , pipe . Reader ) , OutputCancel ) ;
2933 }
3034
3135 internal bool HasOutputPipe => _output is not null ;
3236
33- private static async Task CopyOutputAsync ( PhysicalConnection connection , PipeReader from , Stream to )
37+ internal Task CompleteOutputAsync ( Exception ? exception = null )
38+ {
39+ _output ? . Complete ( exception ) ;
40+ return _writeComplete ;
41+ }
42+
43+ private static async Task CopyOutputAsync ( PhysicalConnection connection , PipeReader from )
3444 {
3545 try
3646 {
3747 bool pendingFlush = false ;
38- while ( true )
48+ while ( connection . _ioStream is { } stream )
3949 {
4050 if ( ! from . TryRead ( out var read ) )
4151 {
4252 if ( pendingFlush )
4353 {
44- await to . FlushAsync ( connection . OutputCancel ) . ConfigureAwait ( false ) ;
54+ await stream . FlushAsync ( connection . OutputCancel ) . ConfigureAwait ( false ) ;
4555 pendingFlush = false ;
4656 }
4757 read = await from . ReadAsync ( connection . OutputCancel ) . ConfigureAwait ( false ) ;
@@ -55,7 +65,7 @@ private static async Task CopyOutputAsync(PhysicalConnection connection, PipeRea
5565 {
5666 pendingFlush = true ;
5767 connection . totalBytesSent += segment . Length ;
58- await to . WriteAsync ( buffer . First , connection . OutputCancel ) . ConfigureAwait ( false ) ;
68+ await stream . WriteAsync ( buffer . First , connection . OutputCancel ) . ConfigureAwait ( false ) ;
5969 }
6070 }
6171 else
@@ -66,7 +76,7 @@ private static async Task CopyOutputAsync(PhysicalConnection connection, PipeRea
6676 {
6777 pendingFlush = true ;
6878 connection . totalBytesSent += segment . Length ;
69- await to . WriteAsync ( segment , connection . OutputCancel ) . ConfigureAwait ( false ) ;
79+ await stream . WriteAsync ( segment , connection . OutputCancel ) . ConfigureAwait ( false ) ;
7080 }
7181 }
7282 }
0 commit comments