如何在返回IAsyncAction的函数中进行co_await?

问题描述

这是一个将文件读取到文本框中的简单函数:

IAsyncAction MainPage::OnOpenAppBarButtonClick(IInspectable const& /*sender*/,RoutedEventArgs const& /*args*/)
{
    FileOpenPicker picker{};
    picker.FileTypeFilter().Append(L".txt");

    StorageFile storageFile = co_await picker.PickSingleFileAsync();

    if (storageFile)
    {
        txtbox().Text(co_await FileIO::ReadTextAsync(storageFile));
    }
}

这过去工作正常。据我了解,当我们实际上并不从协程返回值时,返回类型为IAsyncAction。今天,我更新了WinRT插件,现在它失败并显示错误:

错误C3773:在这种情况下使用'co_await'是C ++ 20中的不一致扩展

并要求我使用/await来编译代码。使用该编译器开关,它确实可以编译并运行良好,但是上面的代码有什么不合格之处,以及编写此函数的合格方式是什么?

Microsoft在其pipe中有一个非常相似的示例:

#include <iostream>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Web.Syndication.h>

using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Web::Syndication;

void PrintFeed(SyndicationFeed const& syndicationFeed)
{
    for (SyndicationItem const& syndicationItem : syndicationFeed.Items())
    {
        std::wcout << syndicationItem.Title().Text().c_str() << std::endl;
    }
}

IAsyncAction ProcessFeedAsync()
{
    Uri rssFeedUri{ L"https://blogs.windows.com/feed" };
    SyndicationClient syndicationClient;
    SyndicationFeed syndicationFeed{ co_await syndicationClient.RetrieveFeedAsync(rssFeedUri) };
    PrintFeed(syndicationFeed);
}

int main()
{
    winrt::init_apartment();

    auto processOp{ ProcessFeedAsync() };
    // do other work while the feed is being printed.
    processOp.get(); // no more work to do; call get() so that we see the printout before the application exits.
}

使用/std:c++latest(C ++ 20)编译时出现相同错误。

主要问题是如何以一致的方式编写第一个示例函数。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)