python - 何时使用 await 和 asyncio.create_task()?
问题描述
假设我有发布者发布消息和消费者使用它并调用数据库保存方法,那么我应该使用哪个
await save(obj)
或者
asyncio.create_task(save(obj))
为什么?
解决方案
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:
- 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.
- 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?
推荐阅读
- java - 即使一切正常,Selenium testNG 断言也会破坏脚本
- java - 指定为非 null 的 Java 参数为 null IllegalException 方法 kotlin.jvm.internal.Intrinsics
- python - OSX 与 RPi 的内存处理
- javascript - Html-JS:用 js 显示多个 div 的问题
- c# - How do I write a unit test for this method that is called inside a loop?
- ios - Add a refresh control to a horizontal scrollview with page control
- ios - Swift - UISearchController Results displayed Large spacing between search bar and TableView Cells
- python - AttributeError:“DatasetSeries”对象没有属性“all_data”
- c# - Add an Node by index to custom LinkedList, with shift to right
- reactjs - ComponentDidMount not firing in ReactJS