微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在返回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 举报,一经查实,本站将立刻删除。