Skip to content

Commit ad653e1

Browse files
authored
Uni-50101-Fixing_the_domain_reload_crash_on_second_init
Now calling PythonEngine.Shutdown on domain reload
2 parents 3eb7e58 + c0729f3 commit ad653e1

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/runtime/pythonengine.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,19 @@ public static void Initialize(bool setSysArgv = true)
145145
Initialize(Enumerable.Empty<string>(), setSysArgv: setSysArgv);
146146
}
147147

148+
/// <summary>
149+
/// On Domain Unload Event Handler
150+
/// </summary>
151+
/// <remarks>
152+
/// Performs necessary tasks (shutdown) when the current app domain
153+
/// gets unloaded, leaving the engine, the runtime and the Python
154+
/// interpreter in consistent states
155+
/// </remarks>
156+
private static void OnDomainUnload(object sender, EventArgs e)
157+
{
158+
Shutdown();
159+
}
160+
148161
/// <summary>
149162
/// Initialize Method
150163
/// </summary>
@@ -158,6 +171,9 @@ public static void Initialize(IEnumerable<string> args, bool setSysArgv = true)
158171
{
159172
if (!initialized)
160173
{
174+
// Make sure we shut down properly on app domain reload
175+
System.AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload);
176+
161177
// Creating the delegateManager MUST happen before Runtime.Initialize
162178
// is called. If it happens afterwards, DelegateManager's CodeGenerator
163179
// throws an exception in its ctor. This exception is eaten somehow
@@ -294,6 +310,9 @@ public static void Shutdown()
294310
{
295311
if (initialized)
296312
{
313+
// Make sure we shut down properly on app domain reload
314+
System.AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload;
315+
297316
PyScopeManager.Global.Clear();
298317
Marshal.FreeHGlobal(_pythonHome);
299318
_pythonHome = IntPtr.Zero;

0 commit comments

Comments
 (0)