如果我有以下代码示例
async def coro():
# Cancelled error could be raised here
await asyncio.sleep(1)
# Or here
await asyncio.shield(
another_coro()
)
# Or here
async def wait_on_it(loop):
f = loop.create_task(coro())
# Pretend f may or may not happen, I just sleep in this example
await asyncio.sleep(1)
if not f.done():
f.cancel() # Will raise CancelledError when some await finishes in coro()
如何确定受保护的任务是否实际运行?如果已执行屏蔽任务,则必须执行重要的逻辑。也许屏蔽该功能不是正确的方法?
答案 0 :(得分:2)
public function text(User $user)
{
$messages = DB::table('messages')
->join('threads', function($join){
$join->on('messages.thread_id', '=', 'threads.id')
->where('threads.id', '=', $user->threads[0]->id);
})->get();
return view('backend.pending_registrations.textform', compact('user', 'messages'));
}
可以通过修改从调用者接收到的可变对象,将信息传递给调用者:
coro()
由于class Ref:
def __init__(self, **kwargs):
self.__dict__.update(**kwargs)
async def coro(run_ref):
await asyncio.sleep(1)
run_ref.ran_another_coro = True
await asyncio.shield(another_coro())
async def wait_on_it(loop):
run_ref = Ref(ran_another_coro=False)
f = loop.create_task(coro(run_ref))
await asyncio.sleep(1)
if not f.done():
f.cancel()
if run_ref.ran_another_coro:
# ... another_coro() was started
无法暂停,因此如果asyncio.shield
的真实值是wait_on_it
,则可以保证run_ref.ran_another_coro
已经启动。