File tree Expand file tree Collapse file tree 1 file changed +19
-0
lines changed
packages/common-library/src/common_library Expand file tree Collapse file tree 1 file changed +19
-0
lines changed Original file line number Diff line number Diff line change @@ -62,3 +62,22 @@ async def maybe_await(
6262 return await obj
6363 assert not isawaitable (obj ) # nosec
6464 return obj
65+
66+
67+ async def cancel_and_wait (task : asyncio .Task ) -> None :
68+ """Cancels the given task and waits for it to finish.
69+
70+ Accounts for the case where the parent function is being cancelled
71+ and the task is cancelled as a result. In that case, it suppresses the
72+ `asyncio.CancelledError` if the task was cancelled, but propagates it
73+ if the task was not cancelled (i.e., it was still running when the parent
74+ function was cancelled).
75+ """
76+ task .cancel ()
77+ try :
78+ await asyncio .shield (task )
79+ except asyncio .CancelledError :
80+ if not task .cancelled ():
81+ # parent function is being cancelled -> propagate cancellation
82+ raise
83+ # else: task was cancelled, suppress
You can’t perform that action at this time.
0 commit comments