1010
1111namespace PuppeteerSharp
1212{
13- public class Connection
13+ public class Connection : IDisposable
1414 {
1515 public Connection ( string url , int delay , ClientWebSocket ws )
1616 {
@@ -20,6 +20,7 @@ public Connection(string url, int delay, ClientWebSocket ws)
2020
2121 _responses = new Dictionary < int , TaskCompletionSource < dynamic > > ( ) ;
2222 _sessions = new Dictionary < string , Session > ( ) ;
23+ _connectionCloseTask = new TaskCompletionSource < bool > ( ) ;
2324
2425 Task task = Task . Factory . StartNew ( async ( ) =>
2526 {
@@ -32,7 +33,7 @@ public Connection(string url, int delay, ClientWebSocket ws)
3233 private Dictionary < int , TaskCompletionSource < dynamic > > _responses ;
3334 private Dictionary < string , Session > _sessions ;
3435 private bool _closed = false ;
35-
36+ private TaskCompletionSource < bool > _connectionCloseTask ;
3637 #endregion
3738
3839 #region Properties
@@ -80,10 +81,10 @@ public async Task<Session> CreateSession(string targetId)
8081 private void OnClose ( )
8182 {
8283 _closed = true ;
83- if ( Closed != null )
84- {
85- Closed . Invoke ( this , new EventArgs ( ) ) ;
86- }
84+ _connectionCloseTask . SetResult ( true ) ;
85+
86+ Closed ? . Invoke ( this , new EventArgs ( ) ) ;
87+
8788 _responses . Clear ( ) ;
8889 _sessions . Clear ( ) ;
8990 }
@@ -109,7 +110,20 @@ private async Task<object> GetResponseAsync()
109110
110111 while ( ! endOfMessage )
111112 {
112- var result = await WebSocket . ReceiveAsync ( new ArraySegment < byte > ( buffer ) , CancellationToken . None ) ;
113+ var socketTask = WebSocket . ReceiveAsync ( new ArraySegment < byte > ( buffer ) , CancellationToken . None ) ;
114+
115+ await Task . WhenAny (
116+ _connectionCloseTask . Task ,
117+ socketTask
118+ ) ;
119+
120+ if ( _closed )
121+ {
122+ return null ;
123+ }
124+
125+ var result = socketTask . Result ;
126+
113127 endOfMessage = result . EndOfMessage ;
114128
115129 if ( result . MessageType == WebSocketMessageType . Text )
@@ -183,6 +197,12 @@ public static async Task<Connection> Create(string url, int delay = 0)
183197 return new Connection ( url , delay , ws ) ;
184198 }
185199
200+ public void Dispose ( )
201+ {
202+ OnClose ( ) ;
203+ WebSocket . Dispose ( ) ;
204+ }
205+
186206 #endregion
187207 }
188208}
0 commit comments