If cancellation is scheduled for current task, have a way of waiting for the cancellation to take place.
- 主要言語
- Python
- スター
- 2.5k
- フォーク
- 260
- 平均マージ
- 2日 8時間
- マージ済み PR(30日)
- 19
説明
We have a situation where the cancellation of a cancel scope can't be delivered to a task, because it's not yet started. So, anyio will retry the delivering of the cancellation to this task using `call_soon`. (I'm using the asyncio backend.)
This situation causes a race condition where the task is started anyway, even able to create a new task group, spawn sub tasks in there, have these subtasks raise an exception and only after that realizing it was actually cancelled raising an `ExceptionGroup` of both a `CancelledError` and our own exception.
I'd like to be able to check whether cancellation is scheduled for our current task, and if so, don't proceed doing other stuff, but wait for the cancellation to take place.
Apparently, adding an `await sleep(0)` isn't sufficient as a check point to allow the cancellation to take place. The cancellation seems to be scheduled only when doing `await sleep(0.1)` or something like that, but a random sleep value doesn't feel right. As a workaround, I found that the following seems to work:
```python
from anyio.lowlevel import get_async_backend
from anyio import sleep_forever
if get_async_backend().current_effective_deadline() < 0:
await anyio.sleep_forever()
```
However, I'd like to know whether doing something like this makes sense, or whether there's a bug somewhere? I'd expect for instance that entering a task group (`create_task_group().__aenter__()`) would be considered a checkpoint where cancellation can take place, and where we could do exactly the above code.
I've been looking to create a small reproducer script, but so far failed to reproduce the more complex scenario we currently have.
コントリビューションガイド
評価
この issue はまだ評価されていません。