@@ -33,7 +33,6 @@ internal sealed partial class SocketConnection : TransportConnection
3333 private readonly TaskCompletionSource _waitForConnectionClosedTcs = new TaskCompletionSource ( ) ;
3434 private bool _connectionClosed ;
3535 private readonly bool _waitForData ;
36- private int _connectionStarted ;
3736
3837 internal SocketConnection ( Socket socket ,
3938 MemoryPool < byte > memoryPool ,
@@ -68,32 +67,31 @@ internal SocketConnection(Socket socket,
6867
6968 var pair = DuplexPipe . CreateConnectionPair ( inputOptions , outputOptions ) ;
7069
71- _originalTransport = pair . Transport ;
70+ // Set the transport and connection id
71+ Transport = _originalTransport = pair . Transport ;
7272 Application = pair . Application ;
7373
74- Transport = new SocketDuplexPipe ( this ) ;
75-
7674 InitializeFeatures ( ) ;
7775 }
7876
79- public IDuplexPipe InnerTransport => _originalTransport ;
80-
8177 public PipeWriter Input => Application . Output ;
8278
8379 public PipeReader Output => Application . Input ;
8480
8581 public override MemoryPool < byte > MemoryPool { get ; }
8682
87- private void EnsureStarted ( )
83+ public void Start ( )
8884 {
89- if ( _connectionStarted == 1 || Interlocked . CompareExchange ( ref _connectionStarted , 1 , 0 ) == 1 )
85+ try
9086 {
91- return ;
87+ // Spawn send and receive logic
88+ _receivingTask = DoReceive ( ) ;
89+ _sendingTask = DoSend ( ) ;
90+ }
91+ catch ( Exception ex )
92+ {
93+ _trace . LogError ( 0 , ex , $ "Unexpected exception in { nameof ( SocketConnection ) } .{ nameof ( Start ) } .") ;
9294 }
93-
94- // Offload these to avoid potentially blocking the first read/write/flush
95- _receivingTask = Task . Run ( DoReceive ) ;
96- _sendingTask = Task . Run ( DoSend ) ;
9795 }
9896
9997 public override void Abort ( ConnectionAbortedException abortReason )
@@ -108,9 +106,6 @@ public override void Abort(ConnectionAbortedException abortReason)
108106 // Only called after connection middleware is complete which means the ConnectionClosed token has fired.
109107 public override async ValueTask DisposeAsync ( )
110108 {
111- // Just in case we haven't started the connection, start it here so we can clean up properly.
112- EnsureStarted ( ) ;
113-
114109 _originalTransport . Input . Complete ( ) ;
115110 _originalTransport . Output . Complete ( ) ;
116111
@@ -130,7 +125,7 @@ public override async ValueTask DisposeAsync()
130125 }
131126 catch ( Exception ex )
132127 {
133- _trace . LogError ( 0 , ex , $ "Unexpected exception in { nameof ( SocketConnection ) } .") ;
128+ _trace . LogError ( 0 , ex , $ "Unexpected exception in { nameof ( SocketConnection ) } .{ nameof ( Start ) } . ") ;
134129 }
135130 finally
136131 {
0 commit comments