惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
NISL@THU
NISL@THU
MongoDB | Blog
MongoDB | Blog
Microsoft Security Blog
Microsoft Security Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
CERT Recently Published Vulnerability Notes
aimingoo的专栏
aimingoo的专栏
B
Blog RSS Feed
WordPress大学
WordPress大学
Know Your Adversary
Know Your Adversary
The Register - Security
The Register - Security
Jina AI
Jina AI
Spread Privacy
Spread Privacy
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Blog of Author Tim Ferriss
GbyAI
GbyAI
J
Java Code Geeks
S
Securelist
Y
Y Combinator Blog
T
Threat Research - Cisco Blogs
酷 壳 – CoolShell
酷 壳 – CoolShell
Vercel News
Vercel News
W
WeLiveSecurity
Hugging Face - Blog
Hugging Face - Blog
小众软件
小众软件
Martin Fowler
Martin Fowler
TaoSecurity Blog
TaoSecurity Blog
S
Schneier on Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
D
DataBreaches.Net
L
LINUX DO - 热门话题
T
Tailwind CSS Blog
T
Tor Project blog
博客园 - 叶小钗
Blog — PlanetScale
Blog — PlanetScale
I
Intezer
V
V2EX
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
雷峰网
雷峰网
The GitHub Blog
The GitHub Blog
量子位
AI
AI
Cyberwarzone
Cyberwarzone
T
Troy Hunt's Blog
N
News | PayPal Newsroom
H
Help Net Security

The Old New Thing

Why has the display control panel pointer truncation bug gone unfixed for so long? - The Old New Thing Speculating on how the buggy control panel extension truncated a value that it had right in front of it - The Old New Thing The case of the invalid function pointer when shutting down the display control panel - The Old New Thing Microspeak: Double-click and drill down - The Old New Thing Why don't we just make the entire stack out of guard pages? - The Old New Thing The case of the mysterious changes to integers when there shouldn't have been any code generation effect - The Old New Thing I've decoded a #pragma detect_mismatch error and fixed the mismatch, but I still get the error - The Old New Thing The other kind of control flow guard check: The combined validate and call - The Old New Thing How did Windows 95 decide that a setup program ran? - The Old New Thing I opened a file with FILE_FLAG_DELETE_ON_CLOSE, but now I changed my mind - The Old New Thing How did we conclude that CcNamespace.dll was the ringleader of a group of DLLs that unloaded prematurely? - The Old New Thing The case of the thread executing from an unloaded third-party DLL - The Old New Thing It rather involved being on the other side of this airtight hatchway: Changing administrative settings - The Old New Thing 2026 mid-year link clearance - The Old New Thing A compatibility note on the abuse of Windows window class extra bytes - The Old New Thing The evolution of window and class extra bytes in Windows - The Old New Thing The case of the DLL that was not present in memory despite not being formally unloaded, part 2 - The Old New Thing Raymond's hot take on Hainanese chicken - The Old New Thing The case of the DLL that was not present in memory despite not being formally unloaded, part 1 - The Old New Thing Microspeak elaborated: Isn't escrow just a release candidate by another name? - The Old New Thing In memory of the man who put red and green squiggles under words - The Old New Thing What does it mean when the bottom bit of my HMODULE is set? - The Old New Thing Why doesn't Get­Last­Input­Info() return info for the user I'm impersonating? - The Old New Thing Windows stack limit checking retrospective, follow-up - The Old New Thing Retrofitting the WM_COPY­DATA message onto Windows 3.1 - The Old New Thing The time the x86 emulator team found code so bad that they fixed it during emulation - The Old New Thing How can I schedule work on a thread pool with low latency? Understanding the rationale behind a rule when trying to circumvent it What’s the opposite of Clip­Cursor that lets me exclude the cursor from a region? The Microsoft Company Party where everybody played name tag swap Rotation revisited: Shuffling more than three blocks, and other small notes The back cover of C++: The Programming Language also raises questions not answered by the front cover Rotation revisited: Avoiding having to calculate the gcd when doing cycle decomposition Rotation revisited: Cycle decomposition in clang’s libcxx Rotation revisited: A shocking discovery about gcc’s unidirectional rotation algorithm Rotation revisited: Another unidirectional algorithm The placeholder name for the Windows 8 experience was “modern” Sharing the result of a single Windows Runtime IAsyncOperation among multiple coroutines, part 3 Sharing the result of a single Windows Runtime IAsyncOperation among multiple coroutines, part 2 Sharing the result of a single Windows Runtime IAsyncOperation among multiple coroutines, part 1 If C# and JavaScript lets me await a Windows Runtime asynchronous operation more than once, why not C++/WinRT? A hypothetical redesign of System.Diagnostics.Process to avoid confusion over properties that are valid only when you are the one who called Start Why do you say that a COM STA thread must pump messages if I see sample code creating STA threads and not pumping messages? How do I use Win32 structures from the Windows Runtime? What is the history of the ERROR_ARENA_TRASHED error code? The classic TreeView control lets me sort by name or by lParam, but why not both? Just shows that nobody cares about debugging the parity flag any more The case of the Create­File­Mapping that always reported ERROR_ALREADY_EXISTS
Cancellation of Windows Runtime activities is asynchronous - The Old New Thing
Raymond Chen · 2026-06-24 · via The Old New Thing

In the Windows Runtime, there are four interface patterns for representing asynchronous activity.

  No return type With return type T
Without progress IAsyncAction IAsyncOperation<T>
With progress IAsyncActionWithProgress<P> IAsyncOperationWithProgress<T, P>

For the purpose of this discussion, I will collectively call these “asynchronous activities”.

One of the things you can do with asynchronous activities is cancel them, by calling the Cancel 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.²

Asynchronous cancellation is important for avoiding deadlocks.

Most of the time, the scenarios involve cross-thread synchronous calls, but here’s an extremely obvious way it can happen.

Suppose that you have registered a progress callback on your asynchronous activity with progress.

// C#
async Task DoSomethingWithTimeoutAsync()
{
    var op = DoSomethingAsync();
    op.Progress = (sender, p) => {
        UpdateProgress(p);
        if (p >= 0.5) {
            sender.Cancel();
        }
    };
    try {
        await op;
    } catch (TaskCanceledException) {
        // ignore cancellation
    }
}

// C++/WinRT
winrt::fire_and_forget Widget::DoSomethingWithTimeoutAsync()
{
    auto op = DoSomethingAsync();
    op.Progress([&](auto&& sender, auto p) {
        this->UpdateProgress(p);
        if (p >= 0.5) {
            sender.Cancel();
        }
    });

    try {
        co_await op;
    } catch (winrt::hresult_canceled const&) {
        // ignore cancellation
    }
    co_return;
}

The code calls DoSomethingAsync() and attaches a progress callback which cancels the operation once the progress reaches 50%. If the Cancel() method waited for outstanding progress callbacks to completed, you have a deadlock: The Cancel() is waiting for the progress callback to complete. But the progress callback is itself calling Cancel()

To avoid deadlocks when cancellation occurs while a progress callback is in progress, the cancellation method doesn’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.

// C#

async Task DoSomethingWithTimeoutAsync()
{
    var op = DoSomethingAsync();
    bool canceled = false;
    op.Progress = (sender, p) => {
        if (!canceled) {
            UpdateProgress(p);
            if (p >= 0.5) {
                canceled = true;
                sender.Cancel();
            }
        }
    };
    try {
        await op;
    } catch (TaskCanceledException) {
        // ignore cancellation
    }
}

// C++/WinRT

winrt::fire_and_forget Widget::DoSomethingWithTimeoutAsync()
{
    auto op = DoSomethingAsync();
    bool canceled = false;
    op.Progress([&](auto&& sender, auto p) {
        if (!canceled) {
            this->UpdateProgress(p);
            if (p >= 0.5) {
                canceled = true;
                sender.Cancel();
            }
        }
    });

    try {
        co_await op;
    } catch (winrt::hresult_canceled const&) {
        // ignore cancellation
    }
    co_return;
}

(The canceled variable doesn’t need to be atomic because progress callbacks do not overlap.)

Notice in the C++/winRT version that even after we call Cancel(), we wait for the co_await op to report completion before we return. Otherwise, the Progress callback will access an already-destroyed canceled variable.

¹ This is also the cancellation model for I/O and RPC: 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.

² You might try to solve this by saying “Cancellation is asynchronous if the Cancel is issued from the same thread as the progress event”, but that doesn’t help in this case, which is more realistic:

// C#
async void CancelAfter(IAsyncInfo op, TimeSpan delay)
{
    co_await Task.Delay(delay);
    op.Cancel();
}

async Task DoSomethingWithTimeoutAsync()
{
    var op = DoSomethingAsync();
    op.Progress = (sender, p) => {
        Invoke(() => UpdateProgress(p));
    };
    CancelAfter(op, TimeSpan.FromSeconds(5));
    try {
        await op;
    } catch (TaskCanceledException) {
        // ignore cancellation
    }
}

Suppose the Progress event is raised on a background thread at 4.9999 seconds. Before the lambda can call Invoke(), the CancelAfterDelay timeout elapses, and the UI thread calls Cancel(). 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.

Category

Topics

Author

Raymond Chen

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.