这段代码的Python等价物是什么?
var firstTask = new Task(() => Foo());
var secondTask = firstTask.ContinueWith((fooResult) => Bar(fooResult));
firstTask.Start();
我认为它使用的是asyncio库。我知道如何在Python中创建一个任务,但我找不到一个与C#的ContinueWith()
做同样事情的简单例子。答案 0 :(得分:1)
您可以使用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()
Bar()
协程。然后将lambda的结果安排为要运行的新任务。Foo()
任务;当该任务完成时,将调用Bar()
回调来运行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