在看到关于协程的helloworld的时候,发现微软的例子,编译运行总会抛出异常。根本感觉不到在协程函数里面调用co_await会suspend 协程函数,调用函数会继续的场景。
其实winrt里面大量的函数都是返回异步操作,可以搞个http来替代SyndicationClient
微软的例子如下:
Uri rssFeedUri{ L"https://blogs.windows.com/feed" };
SyndicationClient syndicationClient;
SyndicationFeed syndicationFeed{ co_await syndicationClient.RetrieveFeedAsync(rssFeedUri) }; PrintFeed(syndicationFeed);
稍微再改造下代码
int main()
{
winrt::init_apartment();
try {
std::cout << "before call coroutine\n";
auto processOp{ ProcessFeedAsync() };
std::cout << "after call coroutine\n";
// do other work while the feed is being printed.
processOp.get(); // no more work to do; call get() so that we see
}
catch (const winrt::hresult_error& ex)
{
std::cout << "Caught exception: " << winrt::to_string(ex.message()).c_str() << std::endl;
exit(-1);
}
}
main函数调用协程函数,如果协程函数suspend,main 函数是调用者,会继续运行
重写ProcessFeedAsync函数,使用http来获取请求
IAsyncAction ProcessFeedAsync()
{
Uri rssFeedUri{ L"https://www.sina.com" };
SyndicationClient syndicationClient;
HttpClient httpClient;
std::cout << __LINE__ << std::endl;
auto ret = co_await httpClient.GetStringAsync(rssFeedUri);
std::cout << __LINE__ << std::endl;
}
最终函数的输出
before call coroutine
37
after call coroutine
39
这样就验证了在协程函数里面挂起,调用函数会继续running。