diff --git a/Tests/TerminalGuiFluentTesting/GuiTestContext.cs b/Tests/TerminalGuiFluentTesting/GuiTestContext.cs index c79bc7477..773a4c97d 100644 --- a/Tests/TerminalGuiFluentTesting/GuiTestContext.cs +++ b/Tests/TerminalGuiFluentTesting/GuiTestContext.cs @@ -21,6 +21,7 @@ public class GuiTestContext : IDisposable private readonly StringBuilder _logsSb; private readonly V2TestDriver _driver; private bool _finished; + private readonly object _threadLock = new (); internal GuiTestContext (Func topLevelBuilder, int width, int height, V2TestDriver driver) { @@ -42,46 +43,49 @@ public class GuiTestContext : IDisposable var booting = new SemaphoreSlim (0, 1); - // Start the application in a background thread - _runTask = Task.Run ( - () => - { - try + lock (_threadLock) + { + // Start the application in a background thread + _runTask = Task.Run ( + () => { - ApplicationImpl.ChangeInstance (v2); + try + { + ApplicationImpl.ChangeInstance (v2); - ILogger logger = LoggerFactory.Create ( - builder => - builder.SetMinimumLevel (LogLevel.Trace) - .AddProvider (new TextWriterLoggerProvider (new StringWriter (_logsSb)))) - .CreateLogger ("Test Logging"); - Logging.Logger = logger; + ILogger logger = LoggerFactory.Create ( + builder => + builder.SetMinimumLevel (LogLevel.Trace) + .AddProvider (new TextWriterLoggerProvider (new StringWriter (_logsSb)))) + .CreateLogger ("Test Logging"); + Logging.Logger = logger; - v2.Init (null, GetDriverName ()); + v2.Init (null, GetDriverName ()); - booting.Release (); + booting.Release (); - Toplevel t = topLevelBuilder (); - t.Closed += (s, e) => { _finished = true; }; - Application.Run (t); // This will block, but it's on a background thread now + Toplevel t = topLevelBuilder (); + t.Closed += (s, e) => { _finished = true; }; + Application.Run (t); // This will block, but it's on a background thread now - t.Dispose (); - Application.Shutdown (); - } - catch (OperationCanceledException) - { } - catch (Exception ex) - { - _ex = ex; - } - finally - { - ApplicationImpl.ChangeInstance (origApp); - Logging.Logger = origLogger; - _finished = true; - } - }, - _cts.Token); + t.Dispose (); + Application.Shutdown (); + } + catch (OperationCanceledException) + { } + catch (Exception ex) + { + _ex = ex; + } + finally + { + ApplicationImpl.ChangeInstance (origApp); + Logging.Logger = origLogger; + _finished = true; + } + }, + _cts.Token); + } // Wait for booting to complete with a timeout to avoid hangs if (!booting.WaitAsync (TimeSpan.FromSeconds (5)).Result)