代码之家  ›  专栏  ›  技术社区  ›  user2023861

Python相当于C的ContinueWith()

  •  0
  • user2023861  · 技术社区  · 7 年前

    var firstTask = new Task(() => Foo());
    var secondTask = firstTask.ContinueWith((fooResult) => Bar(fooResult));
    firstTask.Start();
    

    我认为它会使用异步库。我知道如何用Python创建一个任务,但是我找不到一个简单的例子来说明与C#的ContinueWith()做相同的事情

    1 回复  |  直到 7 年前
        1
  •  1
  •   Martijn Pieters    7 年前

    你可以用 Future.add_done_callback() callback registration function 要执行同样的操作;回显lambda函数支持将是:

    import asyncio
    
    def continue_task_with(task, callback, *, loop=None):
        """When a task completes, schedule a new task.
    
        The new task is created by calling the callback with the result of
        the first task.
    
        """
        def done_callback(fut):
            asyncio.ensure_future(callback(fut), loop=loop)
        task.add_done_callback(done_callback)
    
    foo_task = asyncio.ensure_future(foo())
    continue_task_with(foo_task, lambda result: bar(result))
    asyncio.get_event_loop().run_forever()
    

    所以这个:

    • Foo()
    • 回调接收任务对象,并将该任务对象作为第一个参数传递给lambda,lambda创建 Bar()
    • 任务;当该任务完成时 调用回调以运行 巴() .

    演示:

    >>> async def foo():
    ...     print('Running foo')
    ...     await asyncio.sleep(1)
    ...     print('Completing foo')
    ...     return 42
    ...
    >>> async def bar(foo_task):
    ...     print('Running bar')
    ...     if not (foo_task.cancelled() or foo_task.exception()):
    ...         print('Foo completed successfully, it received', foo_task.result())
    ...     asyncio.get_event_loop().stop()
    ...
    >>> foo_task = asyncio.ensure_future(foo())
    >>> continue_task_with(foo_task, lambda result: bar(result))
    >>> asyncio.get_event_loop().run_forever()
    Running foo
    Completing foo
    Running bar
    Foo completed successfully, it received 42