首页 > 解决方案 > C++/WinRT:我可以等待来自多个协程调用的单个 IAsyncAction 句柄吗?

问题描述

我有 coroutine IAsyncAction Foo,它将在我的程序开始时调用一次。

我也有协程IAsyncAction Bar,它会被任意调用多次,并且必须Foo在某个时候等待。

多个电话可以Bar等待Foo这样的单个电话吗?

IAsyncAction m_fooAction = Foo();

(后来,在Bar……内)

co_await m_fooAction;

我试过这个,但我一直收到错误:( A delegate was assigned when not allowed请参阅https://docs.microsoft.com/en-us/uwp/cpp-ref-for-winrt/error-handling/hresult-illegal-delegate-assignment)。

请注意:此开发是针对 Windows 8 桌面应用程序,因此不能使用CoreDispatcher也不DispatcherQueue.

标签: c++asynchronousc++-winrt

解决方案


根据 C++/WinRT 作者的说法,IAsyncAction类似的接口只能有一个等待者。

作为替代方案,他们建议使用内核句柄。 https://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/concurrency-2#awaiting-a-kernel-handle

更新:来自 Raymond Chen (MSFT):

Possible workarounds:

1. Write your own custom object that supports multi-awaiting.
2. Use an existing object that supports multi-awaiting (such as `Concurrency::task`).
3. Use a kernel handle and `resume_on_signal`.

Option 3 is probably simplest.

选项 3 适用于我的情况。


推荐阅读