Asyncio tasks getting cancelled

Léo El Amri leo at superlel.me
Mon Nov 5 15:10:02 EST 2018


On 05/11/2018 16:38, ike at koeln.ccc.de wrote:
> I just saw, actually
> using the same loop gets rid of the behavior in this case and now I'm
> not sure about my assertions any more.

It's fixing the issue because you're running loop with the
run_forever(). As Ian and myself pointed out, using both asyncio.run()
and loop.run_forever() is not what you are looking for.

> Yet it still looks like asyncio
> doen'st keep strong references.

You may want to look at PEP 3156. It's the PEP defining asyncio.
Ian made a good explanation about why your loop wasn't running the
coroutine scheduled from main().

>> This should indeed fix the issue, but this is definitely not what one is
>> looking for if one really want to _schedule_ a coroutine.
> 
> Which is what I want in this case. Scheduling a new (long-running) task
> as a side effect, but returning early oneself. The new task can't be
> awaited right there, because the creating one should return already.
> 
>> If the goal here is for the task created by main() to complete before
>> the loop exits, then main() should await it, and not just create it
>> without awaiting it.
> 
> So if this happens somewhere deep in the hirarchy of your application
> you would need some mechanism to pass the created tasks back up the
> chain to the main function?

Sorry, I don't get what is you're trying to express.

Either you await for a coroutine, which means the calling one is
"paused" until the awaited coroutine finish its job, either you schedule
a coroutine, which means it will be ran once the already stacked
events/coroutines on the loop are all ran.

In your case, you probably want to change

> loop = asyncio.get_event_loop()
> asyncio.run(main())
> loop.run_forever()

to

> loop = asyncio.get_event_loop()
> loop.create_task(main())
> loop.run_forever()

- Léo

[1] https://www.python.org/dev/peps/pep-3156/



More information about the Python-list mailing list