首页 > 解决方案 > 何时使用 await 和 asyncio.create_task()?

问题描述

假设我有发布者发布消息和消费者使用它并调用数据库保存方法,那么我应该使用哪个
await save(obj)
或者
asyncio.create_task(save(obj))
为什么?

标签: pythonasynchronouspython-asyncio

解决方案


I don't know which one is the correct in your situation. Too little information. The differences are:

Await a coroutine:

....
result = await save(obj)
...

This will wait until save finishes before execution will continue with the next statement. In that time other tasks may run. Finally the value that save returns will be stored to result. Of course, you don't have to store the value, if you don't care. If an exception in save occurs, it will be propagated to the await statement and can (or should) be handled there.


Spawn a task:

...
task = asyncio.create_task(save(obj))
...

This will create a task and immediately continue with the next statement. A new task is not started immediately. It has a chance to run at the first await in the current task.

A task is "fire and forget". Unless you explicitly wait for its termination and retrieve the result, you will not receive the result, nor any exception that might have occurred. In case of an exception asyncio only prints a warning at the program end.


To select the right approach, you need to consider:

  1. awaited coroutine:
  • the current task cannot do anything else while it is busy running the save coroutine. Is it OK? In other words, if the application should react in some way in that time, some other tasks must be responsible for it.
  1. spawned task:
  • can save handle errors (e.g. recover, terminate the application if appropriate or at least write a warning to log)?
  • will the application wait for all spawned and running save tasks to finish their work before it terminates?

推荐阅读