{"id":103646,"date":"2020-04-07T07:00:00","date_gmt":"2020-04-07T14:00:00","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/oldnewthing\/?p=103646"},"modified":"2020-04-07T06:34:35","modified_gmt":"2020-04-07T13:34:35","slug":"20200407-00","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20200407-00\/?p=103646","title":{"rendered":"Creating a non-agile delegate in C++\/WinRT, part 2: The synchronous coroutine"},"content":{"rendered":"<p>Last time, we saw that you could <a href=\"https:\/\/devblogs.microsoft.com\/oldnewthing\/20200406-00\/?p=103641\"> use an <code>ICallback\u00adContext<\/code> to run code synchronously in another apartment<\/a> from your delegate, which is important if the code that is calling your delegate is relying on the timing of your return.<\/p>\n<p>We can also express this in the form of a coroutine that operates synchronously.<\/p>\n<p>If we make the <code>await_<\/code><code>suspend<\/code> invoke the handle synchronously, then the continuation of the coroutine runs synchronously with the code that called <code>co_await<\/code>.<\/p>\n<pre>auto resume_synchronous(ICallbackContext* context)\r\n{\r\n  struct awaiter : std::experimental::suspend_always\r\n  {\r\n    ICallbackContext* context;\r\n    bool await_suspend(\r\n        std::experimental::coroutine_handle&lt;&gt; handle)\r\n    {\r\n      InvokeInContext(context, handle);\r\n      return true;\r\n    }\r\n  };\r\n  return awaiter{ context };\r\n}\r\n<\/pre>\n<p>This simplifies the delegate by letting you use <code>co_await<\/code> to do the dirty work.<\/p>\n<pre>deviceWatcher.Added(\r\n    [=, <span style=\"color: blue;\">context = CaptureCurrentApartmentContext()<\/span>]\r\n    (auto&amp;&amp; sender, auto&amp;&amp; info) <span style=\"color: blue;\">-&gt; winrt::fire_and_forget<\/span>\r\n    {\r\n        <span style=\"color: blue;\">co_await resume_synchronous(context.Get());<\/span>\r\n        viewModel.Append(winrt::make&lt;DeviceItem&gt;(info));\r\n    });\r\n<\/pre>\n<p>Even though there is a <code>co_await<\/code>, execution continues synchronously because <code>await_<\/code><code>suspend<\/code> runs the continuous synchronously.<\/p>\n<p>Whether <code>co_await<\/code> resumes synchronously or not\u00b9 is determined by the awaiter. If you <code>co_await<\/code> something whose awaiter resumes asynchronously, then the <code>co_await<\/code> will resume asynchronously.<\/p>\n<pre>deviceWatcher.Added(\r\n    [=, <span style=\"color: blue;\">context = CaptureCurrentApartmentContext()<\/span>]\r\n    (auto&amp;&amp; sender, auto&amp;&amp; info) <span style=\"color: blue;\">-&gt; winrt::fire_and_forget<\/span>\r\n    {\r\n        auto original_context = CaptureCurrentApartmentContext();\r\n        co_await resume_synchronous(context.Get());\r\n        viewModel.Append(make&lt;DeviceItem&gt;(info));\r\n        co_await resume_synchronous(original_context.Get());\r\n        more_stuff();\r\n        auto result = co_await GetMoreDataAsync();\r\n        process_result(result);\r\n    });\r\n<\/pre>\n<p>In the above example, the first two <code>co_await<\/code>s are synchronous, but the third one (<code>co_await GetMoreDataAsync()<\/code>) is presumably asynchronous. This means that the delegate will return at the point of the third <code>co_await<\/code>, and reference parameters (<code>sender<\/code> and <code>info<\/code>) are probably not going to be valid when the coroutine resumes.<\/p>\n<p>\u00b9 Or at all. The built-in awaiter <code>suspend_<\/code><code>always<\/code> suspends and never wakes up.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>It awaits without waiting.<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[25],"class_list":["post-103646","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-code"],"acf":[],"blog_post_summary":"<p>It awaits without waiting.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/103646","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=103646"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/103646\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=103646"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=103646"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=103646"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}