Asyncio.create_task()在回调函数中不能立即执行的问题。
创始人
2024-09-21 05:00:50
0

在回调函数中使用asyncio.ensure_future()函数来调用协程,而不是使用Asyncio.create_task()。因为在回调函数中,事件循环可能已经执行了一部分任务,无法立即执行新的任务,而asyncio.ensure_future()函数可以在事件循环中安排协程的执行。

示例代码:

import asyncio

async def main():
    loop = asyncio.get_running_loop()
    loop.call_soon(cb)
    print("Callback scheduled")

async def cb():
    print("Callback started")
    await asyncio.sleep(1)
    print("Callback finished")

asyncio.run(main())

如果将下面这句话替换为使用Asyncio.create_task()来调用协程,那么程序将会卡住不动。

loop.call_soon(cb)

可以将上面这句话改为下面这句话,使用asyncio.ensure_future()来调用协程。

asyncio.ensure_future(cb())

相关内容

热门资讯

透视好友房!破解辅助插件wep... 透视好友房!破解辅助插件wepoker,wepoker透视脚本免费使用视频(透视)曝光教程(有挂详情...
透视科技!aapoker辅助插... 透视科技!aapoker辅助插件工具,We poker辅助器下载,新版2025教程(有挂教程);aa...
透视总结!wepoker轻量版... 透视总结!wepoker轻量版辅助,wepoker怎么挂飞机(透视)透明教程(有挂黑科技);1、这是...
透视好友!德州局透视脚本免费版... 透视好友!德州局透视脚本免费版下载手机版,aapoker发牌逻辑,2025教程(有挂内幕)1、起透看...
透视教程!wepoker怎么看... 透视教程!wepoker怎么看牌型,wepoker辅助器激活码(透视)wpk教程(有挂详情)1、进入...
透视辅助!hhpoker透视脚... 透视辅助!hhpoker透视脚本下载,wepoker私人局可以透视,技巧教程(有挂技巧)1、完成we...
透视工具!wepoker怎么设... 透视工具!wepoker怎么设置盖牌,wepoker黑侠破解,教你攻略(有挂秘籍);1、首先打开we...
透视计算!破解辅助插件wepo... 透视计算!破解辅助插件wepoker,wepoker黑侠破解(透视)普及教程(有挂揭秘)1、破解辅助...
透视挂!wepoker透视底牌... 透视挂!wepoker透视底牌脚本,wepoker手机版辅助,德州教程(有挂攻略);1、下载好wep...
透视计算!wepoker国外版... 透视计算!wepoker国外版透视,wepoker私人定制透视(透视)德州教程(有挂介绍);wepo...