当另一个线程请求 CancellationToken 的注册回调时,会在哪个线程上调用它?

问题描述 投票:0回答:1

假设我有一个任务在另一个线程中运行,并在该线程执行期间注册了取消回调(来自

Register
)。

然后

CancellationTokenSource
的所有者从主线程调用
Cancel
。取消回调在何处/何时被调用?在请求取消的主线程中,还是在注册的后台线程中?

c# multithreading task
1个回答
0
投票

CancellationToken.Register
注册的回调在调用
CancellationTokenSource.Cancel()
的线程上执行。因此,如果您从主线程调用 Cancel,回调将在主线程上执行。它不会在注册回调的后台线程上执行。

一个例子:

var cts = new CancellationTokenSource();
var token = cts.Token;

Task.Run(() =>
{
    token.Register(() =>
    {
        Console.WriteLine($"Callback executed on thread {Thread.CurrentThread.ManagedThreadId}");
    });
    
    Console.WriteLine($"Background thread {Thread.CurrentThread.ManagedThreadId}");
    // Simulate some work
    Thread.Sleep(2000);
});

Console.WriteLine($"Main thread {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(500); // Give the background task some time to start and register the callback
cts.Cancel();

输出为:

Main thread 1
Background thread 20
Callback executed on thread 1

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.