4

我有一个监听特定端口的异步函数。我想一次在几个端口上运行该功能,当用户想要停止在特定端口上侦听时,停止在该端口上侦听的功能。

以前我使用 asyncio 库来完成这个任务,我通过创建具有唯一 ID 作为名称的任务来解决这个问题。

asyncio.create_task(Func(), name=UNIQUE_ID)

由于 trio 使用托儿所生成任务,我可以通过使用nursery.child_tasks 查看正在运行的任务,但这些任务无法命名它们,甚至无法按需取消任务

TL;博士

由于 trio 没有取消特定任务的 cancel() 函数,我如何手动取消任务。

4

1 回答 1

3

简单的。您创建一个取消范围,从任务中返回它,并在需要时取消此范围:

async def my_task(task_status=trio.TASK_STATUS_IGNORED):
    with trio.CancelScope() as scope:
        task_status.started(scope)
        pass  # do whatever

async def main():
    async with trio.open_nursery() as n:
        scope = await n.start(my_task)
        pass  # do whatever
        scope.cancel()  # cancels my_task()

神奇的部分是await n.start(task),它一直等到任务调用task_status.started(x)并返回值x(或者None如果你把它留空)。

于 2020-03-13T18:51:03.540 回答