Skip to content

Commit

Permalink
Merge pull request #69 from UiPath/fix/python_threading_model
Browse files Browse the repository at this point in the history
Python.Activities: Fix threading model for load/execute script
  • Loading branch information
adrian-zanescu authored Oct 16, 2020
2 parents be03730 + e519713 commit 97f06b9
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions Activities/Python/UiPath.Python/Impl/Engine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public Task Release()
public Task<PythonObject> LoadScript(string code, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
return Task.Run(() =>
return RunSTA(() =>
{
using (_py.GIL())
{
Expand All @@ -150,7 +150,7 @@ public Task<PythonObject> LoadScript(string code, CancellationToken ct)
Trace.TraceInformation($"Load script took {sw.ElapsedMilliseconds} ms");
}
}
}, ct);
});
}

public Task<PythonObject> InvokeMethod(PythonObject instance, string method, IEnumerable<object> args, CancellationToken cancellationToken)
Expand Down Expand Up @@ -189,7 +189,7 @@ public Task<PythonObject> InvokeMethod(PythonObject instance, string method, IEn
public Task Execute(string code, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.Run(() =>
return RunSTA(() =>
{
using (_py.GIL())
{
Expand All @@ -210,6 +210,9 @@ public Task Execute(string code, CancellationToken cancellationToken)
Trace.TraceInformation($"Script execution took {sw.ElapsedMilliseconds} ms");
}
}

// used as placeholder
return true;
});
}

Expand Down Expand Up @@ -289,5 +292,28 @@ private string GetInitializationScript()
}
}
#endregion

#region STA
private Task<T> RunSTA<T>(Func<T> func)
{
var tcs = new TaskCompletionSource<T>();
Thread thread = new Thread(() =>
{
try
{
tcs.SetResult(func());
}
catch (Exception e)
{
tcs.SetException(e);
}
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

return tcs.Task;
}
#endregion
}
}

0 comments on commit 97f06b9

Please sign in to comment.