Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Task Cancellation in Asyncio | Advanced Asyncio Patterns
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Python Asyncio Basics

bookTask Cancellation in Asyncio

Understanding how to cancel running tasks is crucial when working with asyncio. Sometimes, you may need to stop a task before it completes—perhaps because its result is no longer needed, it has taken too long, or your application is shutting down. In asyncio, you can cancel a task by calling its cancel() method. When a task is cancelled, it raises an asyncio.CancelledError inside the coroutine, which you can catch and handle if necessary. This allows you to clean up resources or perform any required finalization before the task fully stops. Handling cancellation properly ensures your asynchronous applications remain robust and responsive.

12345678910111213141516171819202122
import asyncio async def long_running_task(): try: print("Task started.") await asyncio.sleep(5) print("Task finished.") except asyncio.CancelledError: print("Task was cancelled.") raise async def main(): task = asyncio.create_task(long_running_task()) await asyncio.sleep(1) # Let the task run for a bit print("Cancelling the task...") task.cancel() try: await task except asyncio.CancelledError: print("Caught task cancellation in main.") await main()
copy

In this example, you create a long-running task and then cancel it after one second. When the task is cancelled, it raises asyncio.CancelledError inside the coroutine, which is caught and handled. This pattern is essential for managing resources and ensuring your program responds properly to changes or user requests.

question mark

What happens when you cancel an asyncio task?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 1

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

bookTask Cancellation in Asyncio

Scorri per mostrare il menu

Understanding how to cancel running tasks is crucial when working with asyncio. Sometimes, you may need to stop a task before it completes—perhaps because its result is no longer needed, it has taken too long, or your application is shutting down. In asyncio, you can cancel a task by calling its cancel() method. When a task is cancelled, it raises an asyncio.CancelledError inside the coroutine, which you can catch and handle if necessary. This allows you to clean up resources or perform any required finalization before the task fully stops. Handling cancellation properly ensures your asynchronous applications remain robust and responsive.

12345678910111213141516171819202122
import asyncio async def long_running_task(): try: print("Task started.") await asyncio.sleep(5) print("Task finished.") except asyncio.CancelledError: print("Task was cancelled.") raise async def main(): task = asyncio.create_task(long_running_task()) await asyncio.sleep(1) # Let the task run for a bit print("Cancelling the task...") task.cancel() try: await task except asyncio.CancelledError: print("Caught task cancellation in main.") await main()
copy

In this example, you create a long-running task and then cancel it after one second. When the task is cancelled, it raises asyncio.CancelledError inside the coroutine, which is caught and handled. This pattern is essential for managing resources and ensuring your program responds properly to changes or user requests.

question mark

What happens when you cancel an asyncio task?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 1
some-alt