如何为 UWP C++/WinRT 应用程序创建 "suitable await_ready function"?

How to create "suitable await_ready function" for UWP C++/WinRT app?

我正在尝试在用户单击我的 XAMAL C++/WinRT UWP 应用程序中的按钮时创建异步事件。我创建了 Windows 具有静态 IAsyncOperation 函数的运行时组件,我用 co_await 调用它,这会产生 IntelliSense 错误:

this co_await expression requires a suitable "await_ready" function and none was found'.

没有构建错误,但在运行时会抛出这样的异常:

Exception thrown at 0x00007FFC4EE3A839 in NOVATeacher.exe: Microsoft C++ exception: winrt::hresult_no_interface at memory location 0x000000A0332FCC60.

我是这样调用函数的:

IAsyncAction MainPage::ClickHandler(IInspectable const&, RoutedEventArgs const&)
{
    co_await resume_background();

    auto login = co_await NOVAUtils::CurrentLoginAsync();
    myButton().Content(box_value(login));
}

这是它的声明方式:

//NOVAUtils.idl
namespace NOVAShared
{
    [default_interface]
    runtimeclass NOVAUtils
    {
        static Windows.Foundation.IAsyncOperation<String> CurrentLoginAsync();
    }
}

//NOVAUtils.h
namespace winrt::NOVAShared::implementation
{
    struct NOVAUtils : NOVAUtilsT<NOVAUtils>
    {
        NOVAUtils() = delete;

        static winrt::Windows::Foundation::IAsyncOperation<hstring> CurrentLoginAsync();
    };
}

//NOVAUtils.cpp
namespace winrt::NOVAShared::implementation
{
    IAsyncOperation<hstring> NOVAUtils::CurrentLoginAsync()
    {
        co_await resume_background();

        static hstring login = []()
        {
            auto users = User::FindAllAsync().get();

            hstring out;
            for_each(begin(users), end(users), [&](User user)
            {
                    hstring dname = unbox_value<hstring>(user.GetPropertyAsync(KnownUserProperties::DisplayName()));
                    out = out + dname + L", ";
            });

            return out;
        }();

        co_return login;
    }
}

CurrentLoginAsync() 的内部显然是错误的,它会给我所有的登录信息,而不是当前的登录信息,但这只是为了现在进行测试。

对于这一行

hstring dname = unbox_value<hstring>(user.GetPropertyAsync(KnownUserProperties::DisplayName()))

user.GetPropertyAsync(KnownUserProperties::DisplayName()) 的结果是 IAsyncOperation<IInspectable>,我们无法将其转换为 hstring 直接。根据您的要求,您可以像下面这样在 GetPropertyAsync 方法后面附加 .get()

user.GetPropertyAsync(KnownUserProperties::DisplayName()).get().

Exception thrown at 0x00007FFC4EE3A839 in NOVATeacher.exe: Microsoft C++ exception: winrt::hresult_no_interface at memory location 0x000000A0332FCC60.

构建错误“winrt::hresult_no_interface”可能是上面mis-used导致的,无法转换IAsuncOperation< IInspectable>hstring.