Presentation is loading. Please wait.

Presentation is loading. Please wait.

Asynchronous programming with C++ UWP

Similar presentations


Presentation on theme: "Asynchronous programming with C++ UWP"— Presentation transcript:

1 Asynchronous programming with C++ UWP
Eric Mittelette, Program Manager (Visual C++) Gor Nishanov, Software Engineer (Visual C++) Peter Torr, Program Manager (Windows)

2 General Visual C++ Improvements
Multi-device development Better IDE support Cross-platform support for iOS and Android Refactor -> Rename function Refactor -> Extract function Standard conformance Improved Intellisense for templates C++17 feature-complete for libraries Debugger improvements Fixed C++11 and C++14 conformance issues Clang/C2 front-end support Visualizations Memory diagnostics Performance Graphics diagnostics Code generation Compiler throughput

3 Async with WinRT

4 Async APIs WinRT contains over 1,300 Async APIs
AcquireConnectionAsync CopyToAsync DeviceInfoSupportsCastingAsync GetAnnotationAsync GetEntryAsync GetScaledImageAsThumbnailAsync LoadFromFileAsync RequestDownloadAndInstallPackageUpdatesAsync ProcessNextFrameAsync SendLicenseFetchRequestAsync SignOutAsync TrySetVideoProfileAsync AddAndShowDeviceAccountsAsync CreateAccountAsync GetAnnotationListAsync GetExtensionPropertiesAsync GetSdpRawAttributesAsync LoadFromStreamAsync ProtectAsync RequestDownloadAndInstallPackageUpdatesForUserAsync SendMessageAndGetReplyAsync SignOutUserAsync TrySetViewAsync CreateAnnotationListAsync DeviceInfoSupportsDialAsync GetAnswerToResetAsync GetFeatureReportAsync GetSessionInitiationProtocolUriAsync LoadFromUriAsync ProtectStreamAsync SendMessageAndGetResultAsync StagePackageAsync TrySetViewBoundsAsync AddAsync CreateAppointmentCalendarAsync DisableAnnotationAsync GetAppAndSupplementalPackageUpdatesAsync GetFileAsync LoadListingInformationAsync ProvisionAsync RequestDownloadPackageUpdatesAsync StageUserDataAsync TrySetWallpaperImageAsync AddAudioEffectAsync DisableAsync GetFileFromApplicationUriAsync GetSessionsAndUnregisteredAccountsAsync LoadListingInformationByKeywordsAsync ProvisionFromXmlDocumentAsync SendMessageAsync StartAppInstallAsync TryShowAsStandaloneAsync AddDatagramSocketAsync CreateAsync DisconnectAsync GetAppAndSupplementalPackageUpdatesForUserAsync RequestDownloadPackageUpdatesForUserAsync SendOutputReportAsync StartAsync TryTiltAsync AddDeviceAsync CreateContactListAsync DisconnectProfileAsync GetFileFromPathAsync GetSessionsAsync LoadListingInformationByProductIdsAsync PullCookiesAsync SendProximityDetectionResponseAsync StartDragAsync TryTiltToAsync AddEffectAsync CreateCopyFromSurfaceAsync DownloadAttachmentAsync GetApplicationLinkAsync GetFilesAsync GetSoftwareBitmapAsync PushCookiesAsync RequestExtensionAsync StartPreviewAsync TryUpdateMeetingResponseAsync AddLicenseAsync CreateDashboardItemUpdaterAsync DownloadMessageAsync GetApplicationTokenBindingKeyAsync GetFirstNameAsync GetSourcesUnseenCountAsync LoadModelFromPackageAsync PutAsync RequestLaunchAsync SendProximityDetectionStartAsync StartPreviewToCustomSinkAsync AddPackageAsync DropAsync GetFolderAsync GetSpecialFolderAsync LoadMoreItemsAsync QueryFileSupportAsync RequestPinChangeAsync TryZoomInAsync AddPackageVolumeAsync CreateDeviceAccountAsync EnableAsync GetApplicationTokenBindingKeyIdAsync GetFolderForUserAsync GetStatisticsAsync LockAsync QueryUriSupportAsync RequestPinResetAsync SendQueryCommandAsync StartProjectingAsync TryZoomOutAsync AddProfileFromObjectAsync CreateDeviceInputNodeAsync EnterAsync GetFolderFromPathAsync GetStatusAsync MakeDefaultAccountAsync ReadAsBufferAsync RequestProductPurchaseAsync SendRegistrationRequestAsync StartRecordToCustomSinkAsync TryZoomToAsync AddProfileFromXmlAsync CreateDeviceOutputNodeAsync ExecuteAsync GetAppListEntriesAsync GetFoldersAsync GetStorageItemsAsync MapAllPixelsToTargetAsync ReadAsInputStreamAsync RequestProductPurchaseByProductIdAndSkuIdAsync UnblockAsync AddStreamSocketListenerAsync CreateDownloadAsync FilterUnsupportedSystemFeaturesAsync GetAppointmentAsync GetForUserAsync GetStreamProtectionInfoAsync MapRegionOfPixelsToTargetAsync ReadAsStringAsync SendRequestAsync StartRecordToStorageFileAsync UnlinkRawContactAsync CreateEndpointPairAsync GetAppointmentCalendarAsync GetFrameAsync ReadAsync RequestRemoveFolderAsync SendResponseAsync UnlockAsync AddVideoEffectAsync CreateEndpointPairForPortsAsync FinalizeAsync GetAppointmentInstanceAsync GetGeopositionAsync GetStringAsync MarkAllAsSeenAsync ReadBatchAsync RequestRemovePackageAsync SendResponseWithPinAsync StartRecordToStreamAsync UnpairAsync AddWebAccountAsync FindAccountAsync GetAppPurchaseCampaignIdAsync GetGeopositionHistoryAsync GetSupportedCastingPlaybackTypesAsync MarkAsSeenAsync ReadBufferAsync RequestSetAsNotificationProviderAsync SendSetCommandAsync StartSoftwareTriggerAsync UnprojectAllPixelsAtCorrelatedDepthAsync AppendLinesAsync CreateFileAsync FindAccountProviderAsync GetGeotagAsync MarkEntriesAsSeenAsync ReadClientCharacteristicConfigurationDescriptorAsync SetAccountPictureAsync StartTetheringAsync AppendTextAsync CreateFileForUserAsync FindAccountsAsync GetAppReceiptAsync GetGlyphThumbnailAsync GetSupportedSymbologiesAsync MarkEntryAsSeenAsync RequestSetImageFeedAsync SetAccountPictureFromStreamAsync StopAsync UnprojectRegionPixelsAtCorrelatedDepthAsync ApplyAsync CreateFileInputNodeAsync FindAllAdaptersAsync GetAppStateAsync GetHtmlFormatAsync MarkFolderAsSeenAsync ReadLinesAsync RequestSignAsync StopPreviewAsync ApproveSessionAsync CreateFileOutputNodeAsync FindAllAsync GetAsync GetIdAsync GetSyncManagerAsync MarkFolderSyncEnabledAsync ReadRecordAsync RequestStartCastingAsync SetAccountPicturesAsync StopProjectingAsync UnprotectAsync AttachAsync CreateFolderAsync FindAllCardsAsync GetAsyncKeyState GetImageAsync GetSyncOnDemandForUserAsync MarkMessageAsBlockedAsync ReadTextAsync RequestStartProjectingAsync SetAccountPicturesFromStreamsAsync StopRecognitionAsync UnprotectStreamAsync AuthenticateAsync CreateFolderForUserAsync FindAllForPackageAsync GetAttestationAsync GetImagePropertiesAsync GetSystemHistoryAsync MarkMessageAsSeenAsync ReadValueAsync RequestStoreAsync StopRecordAsync UpdateAppByPackageFamilyNameAsync AuthenticateDeviceAsync CreateForInPlacePropertyEncodingAsync FindAllInstancesAsync GetAttributedNetworkUsageAsync GetIndexedStateAsync GetTextAsync MarkMessageReadAsync RecognizeAsync RequestTokenAsync SetActiveProfileAsync StopSoftwareTriggerAsync AuthenticateSilentlyAsync FindAllPeersAsync GetInputReportAsync GetThumbnailAsync MarkMessagesAsReadAsync RecognizeWithUIAsync RequestUnconstrainedDownloadsAsync SetActiveSymbologiesAsync StopTetheringAsync UpdateAsync AuthenticateUserAsync CreateForTranscodingAsync FindAllProviderWebAccountsAsync GetAuthorityKeyContainerNameAsync GetInputStreamAsync GetThumbnailsAsync MarkSourcesAsSeenAsync RedeemTokenForFileAsync SetAutoAsync StoreAsync UpdateFirmwareAsync BeginServiceRequest CreateFromFileAsync GetIsAppAllowedToInstallAsync GetTokenSilentlyAsync MeasureAsync RegisterDatagramSocketAsync RequestUnconstrainedUploadsAsync SetBitmapAsync SubmitPropertySetUpdatesAsync UpdateKeyAsync BindEndpointAsync CreateFromHResultAsync FindAllSourcesAsync GetBasicPropertiesAsync GetTransportAsync MergeAndValidateWithDefaultPrintTicketAsync RegisterPackageAsync SetCategoryAsync UpdateMediaResourceAsync BindServiceNameAsync CreateFromIdAsync FindAnnotationListsAsync GetBitmapAsync GetIsApplicableAsync GetTransportsAsync RegisterPackageByFullNameAsync RequestVerificationAsync SetConfigurationAsync SubmitUpdatesAsync UpdatePackageAsync BufferAllAsync CreateFromImageFileAsync FindAnnotationsAsync GetBlobInfoAsync GetItemAsync GetUiccAppsAsync MoveAndReplaceAsync RequestVirtualSmartCardCreationAsync SetEncodingPropertiesAsync SwapDisplaysForViewsAsync UpdateProfileFromObjectAsync BuildChainAsync CreateFromStreamAsync FindAnnotationsByRemoteIdAsync GetBrowsePolicyAsync GetItemCountAsync GetUnfulfilledConsumablesAsync MoveAppointmentAsync RegisterStreamSocketListenerAsync SetGeotagAsync SwitchAsync CancelAsync CreateFromUriAsync GetBufferAsync GetItemsAsync MoveAsync RequestVirtualSmartCardDeletionAsync SetGeotagFromGeolocatorAsync SyncAsync UpdateProfileFromXmlAsync CancelAsyncOperations Creat boxAsync FindAnnotationsForContactAsync GetCachedCapabilitiesAsync GetLastNameAsync GetUnseenCountAsync MovePackageToVolumeAsync RegisterSyncManagerAsync SynthesizeSsmlToStreamAsync UpdateResourceAsync CancelIOAsync CreateMediaResourceAsync GetCandidatesAsync GetLibraryAsync GetUriAsync OpenAsync RegisterTransportAsync ReRegistrationAsync SetImageAsync SynthesizeTextToStreamAsync UpdateResourceItemAsync CaptureAsync CreateProtectedAndOpenAsync FindAppointmentCalendarsAsync GetCapabilitiesAsync GetLibraryForUserAsync GetValueAsFileAsync OpenDrawerAsync ReloadSimulatorAsync ReserveCallResourcesAsync SetImageFileAsync TraceOperationCompletion UpdateSettingsAsync CaptureFileAsync CreatePushNotificationChannelForApplicationAsync GetCapabilitiesFromNetworkAsync GetLinguisticAlternativesAsync GetValueAsStreamAsync OpenKeyPairFromCertificateAsync RemoveDeviceAsync ResetAsync SetImageStreamAsync TranscodeAsync UpdateStatisticsAsync CapturePhotoToStorageFileAsync FindAppointmentsAsync GetVideoPropertiesAsync RemoveEffectAsync ResetStatisticsAsync SetLevelAsync TransmitAsync UpdateWebAccountPropertiesAsync CreatePushNotificationChannelForSecondaryTileAsync FindAppServiceProvidersAsync GetChallengeContextAsync GetMailboxAsync GetViewsAsync OpenReadAsync RemovePackageAsync ResolveRecipientsAsync SetMediaStreamPropertiesAsync TryCancelDownloadMessageAsync CapturePhotoToStreamAsync GetColorProfileAsync GetMeContactAsync GetVoiceCallSupportAsync OpenSequentialReadAsync RemovePackageVolumeAsync ResumeAsync UpdateWnsChannelAsync CapturePreviewToStreamAsync CreateRequestAsync FindChildFoldersAsync GetConfigurationAsync GetMessageAsync GetVoiceCommandAsync OpenTransactedWriteAsync RemoveSlipAsync ResumePickSingleFileAsync SetPackageVolumeOfflineAsync TryCancelMeetingAsync UpgradeToSslAsync CaptureSelectedContentToDataPackageAsync CreateResourceAsync FindConflictAsync GetConnectedProfileAsync GetMessageByGlobalUniqueIdAsync GetWalkingRouteAsync OverAsync RenameAsync ResumeRecordAsync TryCancelSendMessageAsync UriToStreamAsync CreateResponseMessageAsync FindConnectionProfilesAsync GetConnectivityIntervalsAsync GetWalkingRouteFromWaypointsAsync PairAsync RenderAsync RetainDeviceAsync SetPackageVolumeOnlineAsync TryComputeLatestMeshAsync ValidateCertificatesAsync ChangeAdministrativeKeyAsync CreateSocialFeedUpdaterAsync FindContactAnnotationListsAsync GetMessageByRemoteIdAsync PauseAsync RenderToFileAsync RetrieveDeviceAuthenticationDataAsync SetPerAppToPerUserAccountAsync TryCreateFolderAsync VerifyAsync GetContactAsync GetMessageCountsAsync GetWalletItemAsync PauseRecordAsync RenderToStreamAsync TryCreateOrUpdateAppointmentAsync VerifyResponseAsync ChangeAsync CreateStreamedFileAsync FindContactIdsBy Async GetContactFromRemoteIdAsync GetMessagesAsync GetWebLinkAsync PickAsync RenewAttestationAsync RetrieveFeedAsync SetPhraseListAsync VerifySignatureAsync ChangeMessageFlagStateAsync CreateStreamedFileFromUriAsync FindContactIdsByPhoneNumberAsync GetContactListAsync GetMusicPropertiesAsync GoToNextFrameAsync PickContactAsync RenewSystemComponentsAsync RetrieveMediaResourceAsync SetPresetAsync TryDeleteFolderAsync WriteAsync CheckAvailabilityAsync GetContainerInfoAsync GetNameAsync ImportItemAsync PickContactsAsync RepairAsync RetrievePropertiesAsync SetPropertiesAsync TryEmptyFolderAsync WriteBufferAsync CheckHealthAsync CreateUploadAsync FindContactListsAsync GetControllersAsync GetNetworkUsageAsync ImportItemsAsync PickMultipleContactsAsync ReplaceWithStreamedFileAsync RetrieveResourceAsync SetRegionsAsync TryExportAnchorsAsync WriteBytesAsync ClaimDrawerAsync CreateUploadFromStreamAsync FindContactsAsync GetConversationAsync GetOneTimePassCodeAsync ImportPfxDataAsync PickMultipleFilesAsync RetrieveServiceDocumentAsync SetRelativeScrollPositionAsync TryForwardMeetingAsync WriteClientCharacteristicConfigurationDescriptorAsync ClaimPrinterAsync CreateWebAccountWatcherAsync Find MailboxesAsync GetConversationFromThreadingInfoAsync GetOutputStreamAsync IndexFileContentsAsync PickSaveFileAsync ReplaceWithStreamedFileFromUriAsync TryGetAutoReplySettingsAsync ClaimReaderAsync FindExceptionsFromMasterAsync GetParentAsync InitializeAsync PickSingleContactAsync RetrieveStatisticsAsync SetRemoteIdentificationInformationAsync WriteDataAsync ClaimScannerAsync DeAuthenticateDeviceAsync GetCountAsync GetPerUserFromPerAppAccountAsync InsertSlipAsync PickSingleDeviceAsync ReportCompletedAsync RetrySendMessageAsync TryGetDepthCorrelatedCameraIntrinsicsAsync WriteLinesAsync CleanupPackageForUserAsync DecryptAsync FindFileHandlersAsync GetCurrentConfigurationAsync InstallCertificateAsync PickSingleDialDeviceAsync ReportConsumableFulfillmentAsync RunAsync SetScopeAsync WriteTextAsync ClearAsync DecryptTpmAttestationCredentialAsync FindItemsAsync GetPictureAsync InstallCommandDefinitionsFromStorageFileAsync PickSingleFileAsync RunIdleAsync SetSourceAsync TryGetDepthCorrelatedCoordinateMapperAsync WriteToStreamAsync ClearEffectsAsync FindLocalIdsFromRoamingIdAsync GetCurrentDownloadsAsync GetPixelDataAsync PickSingleFolderAsync ReportFailedAsync RunToCompletionAsync SetStateAsync WriteValueAsync ClearPublisherCacheFolderAsync DeleteAllAsync GetCurrentDownloadsForTransferGroupAsync GetPixelsAsync InvalidateCacheAsync PingAsync ReportFailureAsync SaveAppointmentAsync SetValueAsync TryGetItemAsync DeleteAnnotationAsync FindLocalLocationsAsync GetPreviewAsync InvokeScriptAsync PostAsync ReportProgressAsync SaveAsAsync SetVersionAsync TryImportAnchorsAsync ClearRegionsAsync DeleteAppointmentAsync FindLocationsAsync GetCurrentReadingAsync GetPreviewFrameAsync IsContainerAsync PrepareAdvancedPhotoCaptureAsync ReportSuccessAsync SaveAsync SetViewAsync TryLinkContactsAsync ClearStallAsync DeleteAppointmentInstanceAsync FindLocationsAtAsync GetCurrentUploadsAsync GetPrimaryManagedIdentityForNetworkEndpointAsync IsStoreBlockedByPolicyAsync RequestAccessAsync SaveContactAsync SetWebAccountPictureAsync TryMoveAsync ClearTemporaryWebDataAsync FindMailboxesAsync GetCurrentUploadsForTransferGroupAsync IssueCredentialsAsync PrepareFileTranscodeAsync RequestAccessForAppAsync SaveDraftAsync ShowAccountErrorResolverAsync TryMoveFolderAsync ClearViewAsync DeleteAsync FindMessagesAsync GetPrincipalNameAsync IsSupportedAsync PrepareForCustomAnimatedSwitchAsync RequestAddFolderAsync SaveEntryAsync TryMoveMessageAsync ClearWebAccountPictureAsync DeleteContactAsync FindNearbyAsync GetCustomerCollectionsIdAsync GetProductReceiptAsync IsSymbologySupportedAsync RequestAnnotationStoreAsync SaveFileAsContainerAsync ShowAccountSettingsAsync TryPartialRepairAsync CloseAndSaveToFileAsync DeleteContainerAsync FindRawContactsAsync GetProfilesAsync LaunchAppForItemAsync PrepareLowLagPhotoCaptureAsync RequestAppLaunchAsync SaveMessageAsync ShowAddAccountAsync TryProposeNewTimeForMeetingAsync CommitAsync DeleteDeviceAccountAsync FindStartIndexAsync GetCustomerPurchaseIdAsync GetPropertiesAsync LaunchAsync RequestAppPurchaseAsync SaveModelToPackageAsync ShowAddAppointmentAsync CompileConstraintsAsync DeleteEntriesAsync FindUnexpandedAppointmentsAsync GetDataAsync GetPropertyAsync LaunchFileAsync PrepareLowLagPhotoSequenceCaptureAsync RequestAsync SavePropertiesAsync ShowAppointmentDetailsAsync TryReduceFacesAsync CompleteUpdatesAsync DeleteEntryAsync GetDataBySessionPortAsync GetProtectionInfoAsync LaunchFolderAsync RequestAttestedVirtualSmartCardCreationAsync SaveToFileAsync ShowAsStandaloneAsync TryRotateAsync ConfigureAccessPointAsync DeleteImportedItemsFromSourceAsync FindUriSchemeHandlersAsync GetDefaultAsync GetProvisioningInfoAsync LaunchFullTrustProcessForAppAsync PrepareLowLagRecordToCustomSinkAsync ScanAsync ShowAsync TryRotateToAsync ConnectAsync FinishAsync GetDefaultPrintTicketAsync GetProxyConfigurationAsync RequestConfirmationAsync ScanFilesToFolderAsync ShowAtAsync TryRunAsync ConnectProfileAsync DeleteLicenses FlushAsync GetDeviceAccountConfigurationAsync GetPublicFolderAsync LaunchFullTrustProcessForCurrentAppAsync PrepareLowLagRecordToStorageFileAsync RequestContentAccessAsync ScanPreviewToStreamAsync ShowComposeNew Async TryRunIdleAsync ConnectProfileWithPasswordCredentialAsync DeleteMessageAsync FocusAsync GetRadiosAsync RequestCreateAsync ScheduleAsync ShowComposeSmsMessageAsync TrySaveAnnotationAsync DeleteMessagesAsync ForwardMessageAsync GetDeviceSelectorFromCastingSourceAsync GetRecordDetailsAsync LaunchUriAsync PrepareLowLagRecordToStreamAsync RequestCreateForSelectionAsync SearchForAllUpdatesAsync ShowEditNewAppointmentAsync TrySaveAsync ConvertBackAsync DeleteMultipleAsync FromBluetoothAddressAsync GetRemainingBytesInQuotaAsync LaunchUriForResultsAsync SearchForUpdatesAsync ShowForSelectionAsync TrySendIOControlAsync ConvertContactToVCardAsync DeleteProfileAsync FromFolderAsync GetDisplayNameAsync LeaveAsync PrepareMediaStreamSourceTranscodeAsync RequestCredentialsAsync SelectNewAsync ShowPrintUIAsync TrySetAutoReplySettingsAsync ConvertVCardToContactAsync DeleteResourceAsync FromHostNameAsync GetDocumentPropertiesAsync GetResourceMapAsync LeaveConversationAsync RequestCustomPromptAsync SelectSettingAsync ShowRemoveAppointmentAsync CopyAndCloseAsync DeleteResourceItemAsync FromIdAsync GetDomainNameAsync GetRestrictionLevelAsync LicenseFetchAsync PreparePageAsync RequestDeleteAsync SendControlInTransferAsync ShowReplaceAppointmentAsync TrySetLockScreenImageAsync CopyAndReplaceAsync DeleteWebAccountAsync FromNetworkAccountIdAsync GetDrivingRouteAsync GetRfcommServicesAsync LoadAddOnProductInfosAsync PrepareStreamTranscodeAsync RequestDeleteForSelectionAsync SendControlOutTransferAsync ShowTimeFrameAsync TrySetPreferredSourceForPictureAsync CopyAsync DenySessionAsync FromSmartCardAsync GetDrivingRouteFromWaypointsAsync GetRfcommServicesForIdAsync LoadAsync PrepareVariablePhotoSequenceCaptureAsync SendFeatureReportAsync SignAsync CopyFromFileAsync DeprovisionAsync GenerateSignatureAsync GetRtfAsync LoadCurrentAsync RequestDisambiguationAsync SendIOControlAsync SignHashedDataAsync TrySetPropertyAsync CopyProtectionAsync DetectFacesAsync GetAccountAsync GetEndpointPairsAsync LoadFileFromContainerAsync ProcessEventAsync SignInAsync TrySetSceneAsync Async APIs WinRT contains over 1,300 Async APIs Any API that might stall the UI is designed to be asynchronous Leads to more responsive applications Apps should never appear “hung” due to disk or network latency Consuming these APIs from C++ can be cumbersome

5 Demo: Opening a JPG Using PPL tasks

6 Async code to open a JPG 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) { create_task(file->OpenReadAsync()).then([this] (Windows::Storage::Streams::IRandomAccessStreamWithContentType^ stream) auto bitmap = ref new BitmapImage(); bitmap->SetSource(stream); theImage->Source = bitmap; });

7 Async code to open a JPG 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) { create_task(file->OpenReadAsync()).then([this] (Windows::Storage::Streams::IRandomAccessStreamWithContentType^ stream) auto bitmap = ref new BitmapImage(); bitmap->SetSource(stream); theImage->Source = bitmap; });

8 Async code to open a JPG 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) { create_task(file->OpenReadAsync()).then([this] (Windows::Storage::Streams::IRandomAccessStreamWithContentType^ stream) auto bitmap = ref new BitmapImage(); bitmap->SetSource(stream); theImage->Source = bitmap; });

9 Async code to open a JPG 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) { create_task(file->OpenReadAsync()).then([this] (Windows::Storage::Streams::IRandomAccessStreamWithContentType^ stream) auto bitmap = ref new BitmapImage(); bitmap->SetSource(stream); theImage->Source = bitmap; });

10 There’s got to be a better way!

11 Coroutines and co_await

12 Code is trivial if synchronous (open JPEG)
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; }

13 Code is trivial if asynchronous (open JPEG)
task<void> ShowImageAsync() { auto picker = ref new FileOpenPicker(); picker->FileTypeFilter->Append(L".jpg"); picker->SuggestedStartLocation = PickerLocationId::PicturesLibrary; auto file = co_await picker->PickSingleFileAsync(); auto stream = co_await file->OpenReadAsync(); auto bitmap = ref new BitmapImage(); bitmap->SetSource(stream); theImage->Source = bitmap; }

14 Demo: Opening a JPG (redux)
Using co_await

15 More complex example: reading a socket
future<void> do_while(function<future<bool>()> body) { return body().then([=](future<bool> notDone) { return notDone.get() ? do_while(body) : make_ready_future(); }); } future<int> tcp_reader(int total) { struct State { char buf[4 * 1024]; int total; Tcp::Connection conn; explicit State(int total) : total(total) {} }; auto state = make_shared<State>(total); return Tcp::Connect(" ", 1337).then( [state](future<Tcp::Connection> conn) { state->conn = std::move(conn); return do_while([state]()->future<bool> { if (state->total <= 0) return make_ready_future(false); return state->conn.read(state->buf, sizeof(state->buf)).then( [state](future<int> nBytesFut) { auto nBytes = nBytesFut.get() if (nBytes == 0) return make_ready_future(false); state->total -= nBytes; return make_ready_future(true); auto tcp_reader(int total) -> future<int> { char buf[4 * 1024]; auto conn = co_await Tcp::Connect(" ", 1337); for (;;) auto bytesRead = co_await conn.Read(buf, sizeof(buf)); total -= bytesRead; if (total <= 0 || bytesRead == 0) return total; }

16 C++ Coroutines in depth

17 Coroutines are popular!
Python: PEP 0492   async def abinary(n): if n <= 0: return l = await abinary(n - 1) r = await abinary(n - 1) return l r HACK (programming language) async function gen1(): Awaitable<int> {   $x =  await Batcher::fetch(1);   $y =  await Batcher::fetch(2); return $x + $y; } C++1z future<string> WaitAsynchronouslyAsync() { co_await sleep_for(10ms); co_return "Finished"s; } DART 1.9 Future<int> getPage(t) async { var c = new http.Client(); try { var r = await c.get(' print(r); return r.length(); } finally { await c.close(); } C# async Task<string> WaitAsynchronouslyAsync() { await Task.Delay(10000); return "Finished"; }

18 Design Principles Scalable Efficient Seamless Open-ended Usable
to billions of concurrent coroutines Efficient resume and suspend operations comparable in cost to a function call Seamless interaction with existing facilities with no overhead Open-ended coroutine machinery allowing library designers to expose high-level semantics such as generators, goroutines, tasks and more Usable in environments where exceptions are forbidden or not available

19 Generalized Function Plain old function Coroutine designer
Task co_await User Generator co_yield Async Generator co_await + co_yield does not care Compiler

20 3 x 2 x 2 Three new keywords Two new concepts Two library types
co_await co_return co_yield [syntactic sugar for: await $p.yield_value(expr)] Two new concepts Awaitable Coroutine Promise Two library types coroutine_handle coroutine_traits

21 C++ Coroutines: Layered complexity
Everybody Safe by default, novice friendly Use coroutines and awaitables defined by standard library, boost and other high quality libraries Power Users Define new awaitables to customize await for their environment using existing coroutine types Experts Define new coroutine types

22 Coroutines and the C++ Standard
TS for C++17 Latest draft: Supported in Visual Studio 2015, Update 2 “Experimental” support with /await flag until standardized Fully supported in Windows Store Apps Clang implementation in progress

23 Call to Action Start using co_await in your Universal Windows Apps
Remember the /await command-line flag! Send us your feedback Windows: Feedback App, choose “Developer Platform” area VC++: See more detailed talks on C++ coroutines Meeting Cpp: – introductory level CppCon: – deep-dive See additional developer content Re-visit //build/ on Channel 9 Continue your education at Microsoft Virtual Academy online

24 Thanks for watching!

25 6/10/ :02 PM © 2016 Microsoft Corporation. All rights reserved. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.


Download ppt "Asynchronous programming with C++ UWP"

Similar presentations


Ads by Google