asyncio cancellation pattern

Joseph L. Casale jcasale at activenetwerx.com
Mon Dec 28 21:56:16 EST 2020


I've started writing some asyncio code in lieu of using threads and
managing concurrency and primitives manually.

Having spent a lot of time using c#'s async implementation, I am struggling
to see an elegant pattern for implementing cancellation. With the necessity
for the loop (that of which I understand) and the disconnect between
context and tasks, how does one act on a failure within a task and invoke
cancellation upwards.

Collecting all tasks and cancelling everything is not appropriate, they may
not necessarily all be part of the graph that needs cancelling.

In c#, we have several patterns available using a cancellation token source
and either passing the token (event only) into the task, or the token source
into the task execution context for signaling during a failure.

Does an easier way then manually creating tasks from coroutines and
tracking them explicitly exist?

Thanks,
jlc


More information about the Python-list mailing list