.. _async-ctrl-c:
-Interrupting async operations using Ctrl-C
-------------------------------------------
+Interrupting async operations
+-----------------------------
If a long running operation is interrupted by a Ctrl-C on a normal connection
running in the main thread, the operation will be cancelled and the connection
will be put in error state, from which can be recovered with a normal
`~Connection.rollback()`.
-If the query is running in an async connection, a Ctrl-C will be likely
-intercepted by the async loop and interrupt the whole program. In order to
-emulate what normally happens with blocking connections, you can use
-`asyncio's add_signal_handler()`__, to call `Connection.cancel()`:
+An async connection provides similar behavior in that if the async task is
+cancelled, any operation on the connection will similarly be cancelled. This
+can happen either indirectly via Ctrl-C or similar signal, or directly by
+cancelling the Python Task via the normal way. Psycopg will ask the
+PostgreSQL postmaster to cancel the operation when it encounters the standard
+Python `CancelledError`__.
-.. code:: python
-
- import asyncio
- import signal
+Remember that cancelling the Python Task does not guarantee that the operation
+will not complete, even if the task ultimately exits prematurely due to
+CancelledError. If you need to know the ultimate outcome of the statement,
+then consider calling `Connection.cancel()` as an alternative to cancelling
+the task.
- async with await psycopg.AsyncConnection.connect() as conn:
- loop.add_signal_handler(signal.SIGINT, conn.cancel)
- ...
+Previous versions of Psycopg recommended setting up signal handlers to
+manually cancel connections. This should no longer be necessary.
-.. __: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.add_signal_handler
+.. __: https://docs.python.org/3/library/asyncio-task.html#task-cancellation
.. index::