From 7736001550dad09fdf9857a7948dbaf25ef7b0bd Mon Sep 17 00:00:00 2001 From: David Lassonde Date: Wed, 4 Jul 2018 15:45:48 -0400 Subject: [PATCH 1/2] * Now calling PythonEngine.Shutdown on app domain unload --- src/runtime/pythonengine.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index a23c7ac79..d8c819308 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -145,6 +145,19 @@ public static void Initialize(bool setSysArgv = true) Initialize(Enumerable.Empty(), setSysArgv: setSysArgv); } + /// + /// On Domain Unload Event Handler + /// + /// + /// Performs necessary tasks (shutdown) when the current app domain + /// gets unloaded, leaving the engine, the runtime and the Python + /// interpreter in consistent states + /// + private static void OnDomainUnload(object sender, EventArgs e) + { + Shutdown(); + } + /// /// Initialize Method /// @@ -158,6 +171,9 @@ public static void Initialize(IEnumerable args, bool setSysArgv = true) { if (!initialized) { + // Make sure we shut down properly on app domain reload + System.AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload); + // Creating the delegateManager MUST happen before Runtime.Initialize // is called. If it happens afterwards, DelegateManager's CodeGenerator // throws an exception in its ctor. This exception is eaten somehow From c0729f3335cc5d849003cf20f12739f2439464a7 Mon Sep 17 00:00:00 2001 From: David Lassonde Date: Thu, 5 Jul 2018 15:37:20 -0400 Subject: [PATCH 2/2] * Unsubscribing the app domain reload event handler on shutdown --- src/runtime/pythonengine.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index d8c819308..f05d641ed 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -310,6 +310,9 @@ public static void Shutdown() { if (initialized) { + // Make sure we shut down properly on app domain reload + System.AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload; + PyScopeManager.Global.Clear(); Marshal.FreeHGlobal(_pythonHome); _pythonHome = IntPtr.Zero;