File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -196,24 +196,29 @@ private static void DisposeFormWhilePumping(Form form)
196196 return ;
197197 }
198198
199- using var pumpContext = new ApplicationContext ( ) ;
200-
201- // Queue the disposal so it executes inside the message loop started below.
202- form . BeginInvoke ( new Action ( ( ) =>
199+ // Post the disposal onto this STA thread's existing queue.
200+ var disposed = false ;
201+ form . BeginInvoke ( ( ) =>
203202 {
204203 try {
205204 if ( ! form . IsDisposed )
206205 form . Dispose ( ) ;
207- } catch {
208- /* ignore disposal errors during teardown */
209- } finally {
210- // End the pump once the handle has been destroyed.
211- pumpContext . ExitThread ( ) ;
212206 }
213- } ) ) ;
214-
215- // Keep the owning apartment pumping until the disposal above completes.
216- Application . Run ( pumpContext ) ;
207+ catch { /* ignore teardown errors */ }
208+ finally { disposed = true ; }
209+ } ) ;
210+
211+ // Pump the queue until the handle is destroyed WITHOUT starting a second
212+ // message loop. StaApartment.ThreadMain already owns the thread's only
213+ // Application.Run loop; calling Application.Run again here throws
214+ // "Starting a second message loop on a single thread ...".
215+ // DoEvents drains queued messages (incl. the cross-apartment UIA release)
216+ // without creating a nested loop.
217+ while ( ! disposed )
218+ {
219+ Application . DoEvents ( ) ;
220+ Thread . Sleep ( 1 ) ; // yield so we don't spin the CPU
221+ }
217222 }
218223 }
219224}
Original file line number Diff line number Diff line change @@ -85,7 +85,7 @@ public void EnsureMapControlCreated()
8585 {
8686 CreateControl ( ) ;
8787
88- // Force the FORM 's own native window handle to exist even though it is never
88+ // Force the Form 's own native window handle to exist even though it is never
8989 // shown. Control.CreateControl() is a no-op while the control is invisible, so
9090 // in headless mode the form otherwise has no handle. That makes the teardown in
9191 // WinFormsTestRunner.DisposeFormWhilePumping fall back to a synchronous
You can’t perform that action at this time.
0 commit comments