wxasync icon indicating copy to clipboard operation
wxasync copied to clipboard

can't stop a started coroutine?

Open karlp opened this issue 2 years ago • 5 comments

I can't see anyway to stop a coroutine started via StartCoroutine() ? I've got a long running task, which runs it's own "while True" loop, with a condition check, but sometimes it dies, and I'd like to restart it, and it sould sometimes just be easier to ask it to stop than to try and pass flags in to it? Is this something possible via existing asyncio primitives, and I'm just doing it wrong? or is this something that needs to be added? (potentially via a token returned from StartCoroutine() ?)

karlp avatar Aug 12 '22 15:08 karlp

Indeed, this is a good question. I'm also looking for a way to stop a Coroutine.

bastien34 avatar Sep 15 '22 21:09 bastien34

Thanks, normally, I would just use a boolean flag like this:

     async def example_coroutine():
            while self.running:
                   print ("test")
                   await asyncio.sleep(1)

and when I need to stop it:

      self.running = False

So, I suppose it would be cleaner to cancel() the task which will raise CancelledError in the coroutine. Since then the task would exit immediately and not have a 0.5second delay (on average). Is that what you would like to happen? Is you could provide me with a use-case example or details about your scenario, that would be useful.

sirk390 avatar Sep 15 '22 21:09 sirk390

HI @karlp @bastien34, have a look at the new api, and tell me if it's good for you:

image

This is pushed to master

sirk390 avatar Sep 19 '22 09:09 sirk390

That looks just great thanks.

I'd worked around it by using a "permanent" coro, that had a flag to check in a while True loop, but it makes it more fragile as it must then handle every possible case that might make it exit. I have a checkbox that enables/disables a background job, and it makes the logic of the background task much easier if it can just "run, and exit if things go badly" knowing that it can be restarted easily.

karlp avatar Sep 19 '22 11:09 karlp

@karlp yes it is indeed an acceptable solution. Thanks for your help. In my case, it was to solve the issue related here https://stackoverflow.com/questions/73730889/wxpython-postevent-from-coroutine-to-a-parent-window-modal/73736712#73736712

bastien34 avatar Sep 19 '22 17:09 bastien34