在c#中为委托回调传递 cancellationtoken 的核心做法是:将 cancellationtoken 作为参数传入委托的构造函数,或在异步方法签名中显式声明该参数。这样,当外部需要取消操作时,只需调用 cancel(),委托内部即可通过检查 iscancellationrequested 属性来响应中断。

Task.Run`1` 如何接收取消令牌
在使用 Task.Run 启动后台任务时,可以通过重载版本直接传入 CancellationToken。这会将令牌传递给底层的线程池工作项,确保任务能感知取消请求。

using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var cts = new CancellationTokenSource();
// 直接传入 token
var task = Task.Run(() =>
{
for (int i = 0; i <h2><code>Func<t>`1` 委托如何携带取消逻辑</t></code></h2><p>对于自定义委托如 <code>Func<t></t></code>,标准泛型定义不包含 <code>CancellationToken</code>。解决方法是定义一个包含该参数的新委托类型,或在 lambda 表达式中捕获外部定义的 <code>CancellationToken</code> 变量。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill14235" title="Huo15 Token Optimizer"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20d79f23518.jpg" alt="Huo15 Token Optimizer" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill14235" title="Huo15 Token Optimizer" class="overflowclass">Huo15 Token Optimizer</a>
<p class="overflowclass">辉火 Token 优化器 — 在不影响 OpenClaw 性能的前提下,系统化扫描、清理、监控工作区 token 消耗。安全模式:默认 dry‑run,先备份,AGENTS 永不自动替换。</p>
</div>
<a rel="nofollow" href="/xiazai/skill14235" title="Huo15 Token Optimizer" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p><img src="https://img.php.cn/upload/article/001/431/639/179619834519520.png?x-oss-process=image/resize,p_40" alt="C#怎么为委托回调传递CancellationToken?"></p><pre class="brush:php;toolbar:false;">using System;
using System.Threading;
class Program
{
static void Main()
{
var cts = new CancellationTokenSource();
var token = cts.Token;
// 使用包含 Token 的自定义委托
ActionWithToken work = () => DoWork(token);
work();
cts.Cancel();
// 再次调用会立即抛出或返回
work();
}
delegate void ActionWithToken();
static void DoWork(CancellationToken token)
{
if (token.IsCancellationRequested)
{
Console.WriteLine("Already cancelled");
return;
}
Console.WriteLine("Executing...");
}
}
CancellationToken.ThrowIfCancellationRequested`1`` 的具体行为
在委托回调内部,调用 ThrowIfCancellationRequested 会在检测到取消信号时立即抛出 OperationCanceledException。这是处理长耗时操作的标准模式,它能确保代码不会继续执行后续逻辑,而是直接跳转到异常处理块。









