diff --git a/src/modules/Elsa.Python/HostedServices/PythonGlobalInterpreterManager.cs b/src/modules/Elsa.Python/HostedServices/PythonGlobalInterpreterManager.cs index 7cda4baf1..4b75d927f 100644 --- a/src/modules/Elsa.Python/HostedServices/PythonGlobalInterpreterManager.cs +++ b/src/modules/Elsa.Python/HostedServices/PythonGlobalInterpreterManager.cs @@ -1,5 +1,6 @@ using Elsa.Python.Options; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Python.Runtime; @@ -11,14 +12,16 @@ namespace Elsa.Python.HostedServices; public class PythonGlobalInterpreterManager : IHostedService { private readonly IOptions _options; + private readonly ILogger _logger; private IntPtr _mainThreadState; /// /// Initializes a new instance of the class. /// - public PythonGlobalInterpreterManager(IOptions options) + public PythonGlobalInterpreterManager(IOptions options, ILogger logger) { _options = options; + _logger = logger; } /// @@ -26,17 +29,28 @@ public class PythonGlobalInterpreterManager : IHostedService { if (!string.IsNullOrEmpty(_options.Value.PythonDllPath)) Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", _options.Value.PythonDllPath); + + try + { + PythonEngine.Initialize(); + _mainThreadState = PythonEngine.BeginAllowThreads(); + } + catch (Exception e) + { + _logger.LogWarning(e, "Failed to initialize Python engine"); + } - PythonEngine.Initialize(); - _mainThreadState = PythonEngine.BeginAllowThreads(); return Task.CompletedTask; } /// public Task StopAsync(CancellationToken cancellationToken) { - PythonEngine.EndAllowThreads(_mainThreadState); - PythonEngine.Shutdown(); + if(_mainThreadState != IntPtr.Zero) + { + PythonEngine.EndAllowThreads(_mainThreadState); + PythonEngine.Shutdown(); + } return Task.CompletedTask; } } \ No newline at end of file