{"id":112465,"date":"2026-06-24T07:00:00","date_gmt":"2026-06-24T14:00:00","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/oldnewthing\/?p=112465"},"modified":"2026-06-25T09:15:53","modified_gmt":"2026-06-25T16:15:53","slug":"20260624-00","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20260624-00\/?p=112465","title":{"rendered":"Cancellation of Windows Runtime activities is asynchronous"},"content":{"rendered":"<p>In the Windows Runtime, there are four interface patterns for representing asynchronous activity.<\/p>\n<table style=\"border-collapse: collapse;\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n<tbody>\n<tr>\n<th>\u00a0<\/th>\n<th>No return type<\/th>\n<th>With return type <tt>T<\/tt><\/th>\n<\/tr>\n<tr>\n<th>Without progress<\/th>\n<td><tt>IAsyncAction<\/tt><\/td>\n<td><tt>IAsyncOperation&lt;T&gt;<\/tt><\/td>\n<\/tr>\n<tr>\n<th>With progress<\/th>\n<td><tt>IAsyncActionWithProgress&lt;P&gt;<\/tt><\/td>\n<td><tt>IAsyncOperationWithProgress&lt;T, P&gt;<\/tt><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>For the purpose of this discussion, I will collectively call these &#8220;asynchronous activities&#8221;.<\/p>\n<p>One of the things you can do with asynchronous activities is cancel them, by calling the <code>Cancel<\/code> method. This method submits a request to cancel, but it does not wait for the operation to acknowledge the cancellation. If you want to wait for the operation to stop executing, you have to wait for it to call the completion callback.\u00b2<\/p>\n<p>Asynchronous cancellation is important for avoiding deadlocks.<\/p>\n<p>Most of the time, the scenarios involve cross-thread synchronous calls, but here&#8217;s an extremely obvious way it can happen.<\/p>\n<p>Suppose that you have registered a progress callback on your asynchronous activity with progress.<\/p>\n<pre>\/\/ C#\r\nasync Task DoSomethingWithTimeoutAsync()\r\n{\r\n    var op = DoSomethingAsync();\r\n    op.Progress = (sender, p) =&gt; {\r\n        UpdateProgress(p);\r\n        if (p &gt;= 0.5) {\r\n            sender.Cancel();\r\n        }\r\n    };\r\n    try {\r\n        await op;\r\n    } catch (TaskCanceledException) {\r\n        \/\/ ignore cancellation\r\n    }\r\n}\r\n\r\n\/\/ C++\/WinRT\r\nwinrt::fire_and_forget Widget::DoSomethingWithTimeoutAsync()\r\n{\r\n    auto op = DoSomethingAsync();\r\n    op.Progress([&amp;](auto&amp;&amp; sender, auto p) {\r\n        this-&gt;UpdateProgress(p);\r\n        if (p &gt;= 0.5) {\r\n            sender.Cancel();\r\n        }\r\n    });\r\n\r\n    try {\r\n        co_await op;\r\n    } catch (winrt::hresult_canceled const&amp;) {\r\n        \/\/ ignore cancellation\r\n    }\r\n    co_return;\r\n}\r\n<\/pre>\n<p>The code calls <code>DoSomethingAsync()<\/code> and attaches a progress callback which cancels the operation once the progress reaches 50%. If the <code>Cancel()<\/code> method waited for outstanding progress callbacks to completed, you have a deadlock: The <code>Cancel()<\/code> is waiting for the progress callback to complete. But the progress callback is itself calling <code>Cancel()<\/code>.\u00b9<\/p>\n<p>To avoid deadlocks when cancellation occurs while a progress callback is in progress, the cancellation method doesn&#8217;t wait for an acknowledgment. If you want to know when the activity is finished, wait for it to complete. If you want to ignore progress reports that arrive after you cancel, you can do that yourself.<\/p>\n<pre>\/\/ C#\r\n\r\nasync Task DoSomethingWithTimeoutAsync()\r\n{\r\n    var op = DoSomethingAsync();\r\n    <span style=\"border: solid 1px currentcolor;\">bool canceled = false;<\/span>\r\n    op.Progress = (sender, p) =&gt; {\r\n        <span style=\"border: solid 1px currentcolor;\">if (!canceled) {<\/span>\r\n            UpdateProgress(p);\r\n            if (p &gt;= 0.5) {\r\n                <span style=\"border: solid 1px currentcolor;\">canceled = true;<\/span>\r\n                sender.Cancel();\r\n            }\r\n        }\r\n    };\r\n    try {\r\n        await op;\r\n    } catch (TaskCanceledException) {\r\n        \/\/ ignore cancellation\r\n    }\r\n}\r\n\r\n\/\/ C++\/WinRT\r\n\r\nwinrt::fire_and_forget Widget::DoSomethingWithTimeoutAsync()\r\n{\r\n    auto op = DoSomethingAsync();\r\n    <span style=\"border: solid 1px currentcolor;\">bool canceled = false;<\/span>\r\n    op.Progress([&amp;](auto&amp;&amp; sender, auto p) {\r\n        <span style=\"border: solid 1px currentcolor;\">if (!canceled) {<\/span>\r\n            this-&gt;UpdateProgress(p);\r\n            if (p &gt;= 0.5) {\r\n                <span style=\"border: solid 1px currentcolor;\">canceled = true;<\/span>\r\n                sender.Cancel();\r\n            }\r\n        }\r\n    });\r\n\r\n    try {\r\n        co_await op;\r\n    } catch (winrt::hresult_canceled const&amp;) {\r\n        \/\/ ignore cancellation\r\n    }\r\n    co_return;\r\n}\r\n<\/pre>\n<p>(The <code>canceled<\/code> variable doesn&#8217;t need to be atomic because progress callbacks do not overlap.)<\/p>\n<p>Notice in the C++\/winRT version that even after we call <code>Cancel()<\/code>, we wait for the <code>co_await op<\/code> to report completion before we return. Otherwise, the <code>Progress<\/code> callback will access an already-destroyed <code>canceled<\/code> variable.<\/p>\n<p>\u00b9 This is also the cancellation model for <a title=\"Ready. cancel. wait for it! (part 1)\" href=\"https:\/\/devblogs.microsoft.com\/oldnewthing\/20110202-00\/?p=11613\"> I\/O<\/a> and <a title=\"Ready. cancel. wait for it! (part 3)\" href=\"https:\/\/devblogs.microsoft.com\/oldnewthing\/20110204-00\/?p=11583\"> RPC<\/a>: The cancellation method submits a cancellation request and returns immediately, and the underlying operation indicates that it has stopped executing by reporting some sort of completion.<\/p>\n<p>\u00b2 You might try to solve this by saying &#8220;Cancellation is asynchronous if the <code>Cancel<\/code> is issued from the same thread as the progress event&#8221;, but that doesn&#8217;t help in this case, which is more realistic:<\/p>\n<pre>\/\/ C#\r\nasync void CancelAfter(IAsyncInfo op, TimeSpan delay)\r\n{\r\n    co_await Task.Delay(delay);\r\n    op.Cancel();\r\n}\r\n\r\nasync Task DoSomethingWithTimeoutAsync()\r\n{\r\n    var op = DoSomethingAsync();\r\n    op.Progress = (sender, p) =&gt; {\r\n        Invoke(() =&gt; UpdateProgress(p));\r\n    };\r\n    CancelAfter(op, TimeSpan.FromSeconds(5));\r\n    try {\r\n        await op;\r\n    } catch (TaskCanceledException) {\r\n        \/\/ ignore cancellation\r\n    }\r\n}\r\n<\/pre>\n<p>Suppose the Progress event is raised on a background thread at 4.9999 seconds. Before the lambda can call <code>Invoke()<\/code>, the <code>Cancel\u00adAfter\u00adDelay<\/code> timeout elapses, and the UI thread calls <code>Cancel()<\/code>. Now you have a deadlock because the Progress event is waiting for the lambda, the lambda is waiting for the Invoke, the Invoke is waiting for the UI thread, the UI thread is waiting for the Cancel, and the Cancel is waiting for the Progress event.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>You&#8217;re asking for it to cancel, but it doesn&#8217;t wait for confirmation.<\/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-112465","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-code"],"acf":[],"blog_post_summary":"<p>You&#8217;re asking for it to cancel, but it doesn&#8217;t wait for confirmation.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/112465","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=112465"}],"version-history":[{"count":1,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/112465\/revisions"}],"predecessor-version":[{"id":112466,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/112465\/revisions\/112466"}],"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=112465"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=112465"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=112465"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}