From e3219bd96988c5890e4ddfeb661c942c0c86d251 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 23 Apr 2017 23:10:52 -0400 Subject: dispose resources on Windows Form exit (#268) --- src/StardewModdingAPI/Program.cs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) (limited to 'src/StardewModdingAPI') diff --git a/src/StardewModdingAPI/Program.cs b/src/StardewModdingAPI/Program.cs index 5cf80448..424e1727 100644 --- a/src/StardewModdingAPI/Program.cs +++ b/src/StardewModdingAPI/Program.cs @@ -61,6 +61,9 @@ namespace StardewModdingAPI /// Whether the game is currently running. private bool IsGameRunning; + /// Whether the program has been disposed. + private bool IsDisposed; + /********* ** Public methods @@ -136,7 +139,7 @@ namespace StardewModdingAPI #endif AppDomain.CurrentDomain.UnhandledException += (sender, e) => this.Monitor.Log($"Critical app domain exception: {e.ExceptionObject}", LogLevel.Error); - // override game & hook events + // override game this.GameInstance = new SGame(this.Monitor); #if SDV_1_2 StardewValley.Program.gamePtr = this.GameInstance; @@ -148,7 +151,10 @@ namespace StardewModdingAPI #endif // hook into game events - this.GameInstance.Exiting += (sender, e) => this.IsGameRunning = false; +#if SMAPI_FOR_WINDOWS + ((Form)Control.FromHandle(this.GameInstance.Window.Handle)).FormClosing += (sender, args) => this.Dispose(); +#endif + this.GameInstance.Exiting += (sender, e) => this.Dispose(); this.GameInstance.Window.ClientSizeChanged += (sender, e) => GraphicsEvents.InvokeResize(this.Monitor, sender, e); GameEvents.InitializeInternal += (sender, e) => this.InitialiseAfterGameStart(); GameEvents.GameLoaded += (sender, e) => this.CheckForUpdateAsync(); @@ -178,7 +184,7 @@ namespace StardewModdingAPI } finally { - this.IsGameRunning = false; + this.Dispose(); } } @@ -207,6 +213,11 @@ namespace StardewModdingAPI /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. public void Dispose() { + if (this.IsDisposed) + return; + this.IsDisposed = true; + + this.IsGameRunning = false; this.LogFile?.Dispose(); this.ConsoleManager?.Dispose(); this.CancellationTokenSource?.Dispose(); -- cgit