如何取消C#中的BeginInvoke操作

c#
808
2024/6/20 5:00:44
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要取消C#中的BeginInvoke操作,可以使用EndInvoke方法,并在调用BeginInvoke后立即调用EndInvoke方法。例如:

IAsyncResult result = this.BeginInvoke(new Action(() => { }));
this.EndInvoke(result);

另外,也可以使用CancellationToken来取消BeginInvoke操作。例如:

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

this.BeginInvoke(new Action(() => {
    if (token.IsCancellationRequested)
    {
        return;
    }

    // 执行需要取消的操作
}), token);

// 取消操作
cts.Cancel();

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C# escape 如何处理特殊字符