@@ -41,25 +41,41 @@ public static async Task<IPlaywright> CreateAsync()
4141 {
4242 var transport = new StdIOTransport ( ) ;
4343 var connection = new Connection ( ) ;
44- transport . MessageReceived += ( _ , message ) =>
44+
45+ EventHandler < byte [ ] > onMessageReceived = ( _ , message ) =>
4546 {
4647 Connection . TraceMessage ( "pw:channel:recv" , message ) ;
4748 connection . Dispatch ( JsonSerializer . Deserialize < PlaywrightServerMessage > ( message , JsonExtensions . DefaultJsonSerializerOptions ) ! ) ;
4849 } ;
49- transport . LogReceived + = ( _ , log ) =>
50+ EventHandler < string > onLogReceived = ( _ , log ) =>
5051 {
5152 // workaround for https://github.com/nunit/nunit/issues/4144
5253 var writer = Environment . GetEnvironmentVariable ( "PWAPI_TO_STDOUT" ) != null ? Console . Out : Console . Error ;
5354 writer . WriteLine ( log ) ;
5455 } ;
55- transport . TransportClosed += ( _ , reason ) => connection . DoClose ( reason ) ;
56+ EventHandler < Exception > onTransportClosed = ( _ , reason ) => connection . DoClose ( reason ) ;
57+
58+ transport . MessageReceived += onMessageReceived ;
59+ transport . LogReceived += onLogReceived ;
60+ transport . TransportClosed += onTransportClosed ;
5661 connection . OnMessage = ( message , keepNulls ) =>
5762 {
5863 var rawMessage = JsonSerializer . SerializeToUtf8Bytes ( message , keepNulls ? connection . DefaultJsonSerializerOptionsKeepNulls : connection . DefaultJsonSerializerOptions ) ;
5964 Connection . TraceMessage ( "pw:channel:send" , rawMessage ) ;
6065 return transport . SendAsync ( rawMessage ) ;
6166 } ;
62- connection . Close += ( _ , reason ) => transport . Close ( reason ) ;
67+ connection . Close += ( _ , reason ) =>
68+ {
69+ // Break Connection<->Transport closure cycles and release the underlying
70+ // process / token / reader task, so that callers who call `Dispose` on a
71+ // short-lived Playwright don't accumulate orphaned graphs.
72+ transport . MessageReceived -= onMessageReceived ;
73+ transport . LogReceived -= onLogReceived ;
74+ transport . TransportClosed -= onTransportClosed ;
75+ connection . OnMessage = null ! ;
76+ transport . Close ( reason ) ;
77+ transport . Dispose ( ) ;
78+ } ;
6379 return await connection . InitializePlaywrightAsync ( ) . ConfigureAwait ( false ) ;
6480 }
6581}
0 commit comments