多任务异步协程实现

import asyncio
import time
headers = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Mobile Safari/537.36'
}
async def request(url):
    print("正在下载%s"%url)
    #asynico中遇到阻塞操作 必须进行手动挂起
    await asyncio.sleep(4) #time.sleep(4) 异步协程中如果出现同步模块相关代码,那么无法实现异步
    print("下载完毕",url)
urls = ["url1",'url2','urls3']
#任务列表:存放多个任务对象
tasks = []
for url in urls:
    c = request(url)
    task = asyncio.ensure_future(c)

    tasks.append(task)
loop = asyncio.get_event_loop()
#固定语法:任务列表封装到asyncio.wait中
loop.run_until_complete(asyncio.wait(tasks))

 

上一篇:C# Tasks


下一篇:C# 多线程处理List数据