Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1077dee

Browse files
committed
asyncio doc: add a section about task cancellation
1 parent 7a55b88 commit 1077dee

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Doc/library/asyncio-dev.rst

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,43 @@ Examples of effects of the debug mode:
4040
<asyncio-logger>`.
4141

4242

43+
Cancellation
44+
------------
45+
46+
Cancellation of tasks is not common in classic programming. In asynchronous
47+
programming, not only it is something common, but you have to prepare your
48+
code to handle it.
49+
50+
Futures and tasks can be cancelled explicitly with their :meth:`Future.cancel`
51+
method. The :func:`wait_for` function cancels the waited task when the timeout
52+
occurs. There are many other cases where a task can be cancelled indirectly.
53+
54+
Don't call :meth:`~Future.set_result` or :meth:`~Future.set_exception` method
55+
of :class:`Future` if the future is cancelled: it would fail with an exception.
56+
For example, write::
57+
58+
if not fut.cancelled():
59+
fut.set_result('done')
60+
61+
Don't schedule directly a call to the :meth:`~Future.set_result` or the
62+
:meth:`~Future.set_exception` method of a future with
63+
:meth:`BaseEventLoop.call_soon`: the future can be cancelled before its method
64+
is called.
65+
66+
If you wait for a future, you should check early if the future was cancelled to
67+
avoid useless operations. Example::
68+
69+
@coroutine
70+
def slow_operation(fut):
71+
if fut.cancelled():
72+
return
73+
# ... slow computation ...
74+
yield from fut
75+
# ...
76+
77+
The :func:`shield` function can also be used to ignore cancellation.
78+
79+
4380
.. _asyncio-multithreading:
4481

4582
Concurrency and multithreading

0 commit comments

Comments
 (0)