我尝试按照本文https://blogs.msdn.microsoft.com/vcblog/2016/04/04/using-c-coroutines-to-simplify-async-uwp-code/中提到的fbilling
进行尝试,但有一些奇怪的编译错误:
co_await
最初,我将以下代码放在构造函数
中C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44,0): Error C2825: '_Ret': must be a class or namespace when followed by '::' (compiling source file MainPage.xaml.cpp)
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44): error C2825: '_Ret': must be a class or namespace when followed by '::' (compiling source file MainPage.xaml.cpp)
MainPage.xaml.cpp(44): note: see reference to class template instantiation 'std::experimental::coroutine_traits<void,::MainPage ^,Windows::UI::Xaml::Navigation::NavigationEventArgs ^>' being compiled
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44,0): Error C2510: '_Ret': left of '::' must be a class/struct/union (compiling source file MainPage.xaml.cpp)
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44): error C2510: '_Ret': left of '::' must be a class/struct/union (compiling source file MainPage.xaml.cpp)
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44,0): Error C2061: syntax error: identifier 'promise_type' (compiling source file MainPage.xaml.cpp)
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44): error C2061: syntax error: identifier 'promise_type' (compiling source file MainPage.xaml.cpp)
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44,0): Error C2238: unexpected token(s) preceding ';' (compiling source file MainPage.xaml.cpp)
哪个不起作用。我的猜测是在构造函数中这是不可能的(显而易见的原因)所以我将#include <experimental\resumable>
#include <pplawait.h>
using namespace concurrency;
MainPage::MainPage()
{
InitializeComponent();
auto my_data_file = co_await Windows::ApplicationModel::Package::Current->InstalledLocation->GetFileAsync("samples.txt");
// Preparing app data structures
}
行移到
co_await
导致上述编译错误。
答案 0 :(得分:3)
我的猜测是,第一个问题是你无法从可恢复的函数返回void
,因为void
没有填充co_await
期望的任何协程特征(如{ {1}},get_return_object
等。)
如果您已经在使用PPL,请返回set_result
:
task<void>
答案 1 :(得分:0)
我找到答案:co_await
只有在我们返回task<>
时才能使用(这是不正确的,请参阅@ DavidHaim的回答)。我想这只是create_task
的语法糖。解决方案是在这种情况下提取返回task<void>
的方法:
#include <experimental\resumable>
#include <pplawait.h>
using namespace concurrency;
MainPage::MainPage()
{
InitializeComponent();
PrepareData();
}
task<void> MainPage::PrepareData()
{
auto my_data_file = co_await Windows::ApplicationModel::Package::Current->InstalledLocation->GetFileAsync("samples.txt");
// Preparing app data structures
}
一些评论:虽然协程功能看起来不错,但它会污染语言。请注意PrepareData()
的正文没有任何return
语句,但签名显示它返回task<void>
,导致我无法识别文章中的要求。