如何取消C#中的BeginInvoke操作

c#
小樊
88
2024-07-18 05:00:44

要取消C#中的BeginInvoke操作,可以使用EndInvoke方法,并在調(diào)用BeginInvoke后立即調(diào)用EndInvoke方法。例如:

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

另外,也可以使用CancellationToken來(lái)取消BeginInvoke操作。例如:

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

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

    // 執(zhí)行需要取消的操作
}), token);

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

0