using Elsa.Python.Options;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Python.Runtime;
namespace Elsa.Python.HostedServices;
///
/// Initializes the Python engine.
///
public class PythonGlobalInterpreterManager : IHostedService
{
private readonly IOptions _options;
private IntPtr _mainThreadState;
///
/// Initializes a new instance of the class.
///
public PythonGlobalInterpreterManager(IOptions options)
{
_options = options;
}
///
public Task StartAsync(CancellationToken cancellationToken)
{
if (!string.IsNullOrEmpty(_options.Value.PythonDllPath))
Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", _options.Value.PythonDllPath);
PythonEngine.Initialize();
_mainThreadState = PythonEngine.BeginAllowThreads();
return Task.CompletedTask;
}
///
public Task StopAsync(CancellationToken cancellationToken)
{
PythonEngine.EndAllowThreads(_mainThreadState);
PythonEngine.Shutdown();
return Task.CompletedTask;
}
}