通用Windows平台(UWP)引入了许多异步api;现在差不多有1700个。事实上,团队将每一个可能需要50ms或更长时间才能完成的API切换到异步模式。
使用异步模式编码不是一件容易的事情,尤其是在C++中,您必须创建一个PPL任务并使用一些LAMBDAS使用一个延续(.To)。实际上,在很多情况下编写代码本身并不是那么难,但是可读性不好。
C++协同程序可以简化异步代码,使代码易于理解、编写和维护。但与其给你一个1000字的描述,不如看一个例子:
在这段代码中,我们尝试使用PickSingleFileAsync和OpenAsync打开一个映像:
void AsyncDemoForBuild::MainPage::PickImageClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { using namespace Windows::UI::Xaml::Media::Imaging; using namespace Windows::Storage::Pickers; using namespace concurrency; auto picker = ref new FileOpenPicker(); picker->FileTypeFilter->Append(L".jpg"); picker->SuggestedStartLocation = PickerLocationId::PicturesLibrary; create_task(picker->PickSingleFileAsync()).then([this] (Windows::Storage::StorageFile^ file) { if (nullptr == file) return; create_task(file->OpenReadAsync()).then([this] (Windows::Storage::Streams::IRandomAccessStreamWithContentType^ stream) { auto bitmap = ref new BitmapImage(); bitmap->SetSource(stream); theImage->Source = bitmap; OutputDebugString(L"1. End of OpenReadAsync lambda. "); }); OutputDebugString(L"2. End of PickSingleFileAysnc lambda. "); }); OutputDebugString(L"3. End of function. "); }
由于异步模型,代码引入了复杂性,但是如果是同步的,它看起来会更好:
//Pseudo Code Void ShowImage() { auto picker = ref new FileOpenPicker(); picker->FileTypeFilter->Append(L”.jpg”); picker->SuggestedStartLocation = PickerLocationId::PicturesLibrary; auto file = picker->PickSingleFile(); auto stream = file->OpenRead(); auto bitmap = ref new BitmapImage(); bitmap->SetSource(stream); theImage->Source = bitmap; }
通过协同程序,我们可以在C++中使用COYAAWEATE,但是我们仍然需要在一个任务中,所以代码可以这样写:
#include <experimental esumable> #include using namespace Platform; task AsyncDemoForBuild::MainPage::PickAnImage() { auto picker = ref new FileOpenPicker(); picker->FileTypeFilter->Append(L".jpg"); picker->SuggestedStartLocation = PickerLocationId::PicturesLibrary; auto file = co_await picker->PickSingleFileAsync(); if (nullptr == file) return; auto stream = co_await file->OpenReadAsync(); auto bitmap = ref new BitmapImage(); bitmap->SetSource(stream); theImage->Source = bitmap; OutputDebugString(L"1. End of OpenReadAsync lambda. "); }
我们可以这样称呼它:
void AsyncDemoForBuild::MainPage::PickImageClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { PickAnImage(); }
正如您在这个示例中看到的,使用COEAWAIT可以使UWP C++代码变得简单很多;几乎和同步形式一样简单。我们还可以看到,COYAAVET可以与C++ +CX代码一起使用,这意味着您可以使用“^”引用而不含糊。
当然,必须使用命令行中的/await选项编译代码:
需要注意的是,在VisualStudio2015中,Update2还可以使用/SDL选项。
这种形式的协同程序(cou-await)是使用协同程序最简单的方法。然而,C++中的Coroutines可以做得更多。例如,您可以:
·定义新的awaitables,以便使用现有的协程类型为您的环境自定义await。
·定义新的协同程序类型。
看看这个 邮递 关于定制的等待者。我们将有更多关于其他异步编码主题的帖子。
注意,协同程序不是C++标准的一部分,但只在TS(技术规范)中找到,需要被视为实验(更多信息)。 在这里 ). 但是,由于我们消除了与中的/RTC和/SDL选项的一些兼容性冲突 VS2015更新2 ,我们考虑合作生产。请让我们知道你的实验,你的问题,以及你发现的任何问题。
我们 录制了一段视频 关于2016年的建造。