1

I am using Python.NET to call the EasyOCR Python library. Depending on the context, the detection can be slow (from 30s to a couple of minutes) and some actions performed by my user could result in the cancellation of the task. As far as I can tell, the cancellation token will cancel the task only at the next C# instruction so I am stuck while the python code is running.

I have seen that there is some similar mechanism on Python side using asyncio but I was wondering if there was any way to avoid the complexity of having extra python logic by being able to somehow "kill" the python process. Or maybe some easy way to somehow share the token.

Amaury Levé
  • 1,459
  • 10
  • 21

2 Answers2

1

A feature very similar to what you are asking has been added to Python.NET recently (you might need to use 3.0 previews though, it probably did not make it into 2.5).

This is the test code, that was added for the feature. I think that is the best reference you will be able to get: https://github.com/pythonnet/pythonnet/pull/1337/files#diff-e846713ba20ecf06af2cc88cc1e92bae49d519998b093d2fb0f7fd6644b10092

Pay attention to the SetUp method too. It shows how to correctly set up multithreading.

LOST
  • 2,956
  • 3
  • 25
  • 40
  • Any idea of the ETA of the v3? And related question, how risky do you think it is to go for this preview in a small prod environment (have you seen a lot of potentially risky PRs merged? Is API likely to change drastically between now and release?) – Amaury Levé Jun 08 '21 at 12:45
  • 1
    ETA would be end of 2021. It would be quite risky at this moment, if you want to keep previews updated. – LOST Jun 09 '21 at 05:40
0

There is no good way to abort a non-cooperating thread/task. There is Thread.Abort, but using it is a bad idea. Your options are more or less

  1. Figure out a way to forward the cancellation request to the python code.
  2. Stop waiting for the result when cancelling the task, but let the task continue to run in the background.
  3. Run the task in a separate process, and kill the process on cancel.
  4. Do not allow the task to be cancelled.
JonasH
  • 28,608
  • 2
  • 10
  • 23
  • Thank you @JonasH. I already considered these options, for #1 it's complex but I have something working. For #2, the task is too resource intensive to be left out. For #3, I didn't consider this, I will have a go. For #4, not an option neither (similar to #2). – Amaury Levé Jun 08 '21 at 08:56