这段代码的Python等价物是什么?
var firstTask = new Task(() => Foo());
var secondTask = firstTask.ContinueWith((fooResult) => Bar(fooResult));
firstTask.Start();
我假设它会使用asyncio库。我知道如何在Python语言中创建任务,但我找不到一个简单的示例来实现与C#的ContinueWith()相同的功能
发布于 2018-06-12 03:37:32
您可以使用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()
协程。然后,Bar()
.的结果被调度为要运行的新任务。然后,
Foo()
任务;当该任务完成时,将调用Bar()
回调来运行lambda演示:
>>> 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
https://stackoverflow.com/questions/50804706
复制相似问题