Browse Source

Refactor direct GIL calls to RunInThreadWithLock

pull/5/head
Ionite 2 years ago
parent
commit
ec86a7f6a1
No known key found for this signature in database
  1. 34
      StabilityMatrix/PyRunner.cs

34
StabilityMatrix/PyRunner.cs

@ -23,8 +23,8 @@ internal static class PyRunner
public static string PipExePath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RelativePipExePath); public static string PipExePath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RelativePipExePath);
public static string GetPipPath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RelativeGetPipPath); public static string GetPipPath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RelativeGetPipPath);
public static PyIOStream StdOutStream; public static PyIOStream? StdOutStream;
public static PyIOStream StdErrStream; public static PyIOStream? StdErrStream;
private static readonly SemaphoreSlim PyRunning = new(1, 1); private static readonly SemaphoreSlim PyRunning = new(1, 1);
@ -158,46 +158,24 @@ internal static class PyRunner
/// Evaluate Python expression and return its value /// Evaluate Python expression and return its value
/// </summary> /// </summary>
/// <param name="expression"></param> /// <param name="expression"></param>
public static async Task<T> Eval<T>(string expression) public static Task<T> Eval<T>(string expression)
{ {
await PyRunning.WaitAsync(); return RunInThreadWithLock(() =>
try
{
return await Task.Run(() =>
{
using (Py.GIL())
{ {
var result = PythonEngine.Eval(expression); var result = PythonEngine.Eval(expression);
return result.As<T>(); return result.As<T>();
}
}); });
} }
finally
{
PyRunning.Release();
}
}
/// <summary> /// <summary>
/// Execute Python code without returning a value /// Execute Python code without returning a value
/// </summary> /// </summary>
/// <param name="code"></param> /// <param name="code"></param>
public static async Task Exec(string code) public static Task Exec(string code)
{ {
await PyRunning.WaitAsync(); return RunInThreadWithLock(() =>
try
{
await Task.Run(() =>
{
using (Py.GIL())
{ {
PythonEngine.Exec(code); PythonEngine.Exec(code);
}
}); });
} }
finally
{
PyRunning.Release();
}
}
} }
Loading…
Cancel
Save