注册取消请求的回叫
了解如何注册当 IsCancellationRequested 属性为 true 时调用的委托。 对创建令牌的对象调用 Cancel 时,值将从 false 更改为 true。 使用此技术可取消本地不支持统一取消框架的异步操作,也可取消阻止可能等待异步操作结束的方法。
注意
某些情况下,当启用“仅我的代码”后,Visual Studio 会在引发异常的行中断运行并显示一条错误消息,该消息显示“用户代码未处理异常”。该错误是良性错误。 可以按 F5 继续运行,并查看下面示例中所示的异常处理行为。 为了阻止 Visual Studio 在第一个错误出现时中断,只需依次转到“工具”、“选项”、“调试”、“常规”下,取消选中“仅我的代码”复选框即可。
示例
在下面的示例中,CancelAsync 方法注册为在通过取消标记请求取消时要调用的方法。
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
class CancelWithCallback
{
static void Main()
{
using var cts = new CancellationTokenSource();
var token = cts.Token;
_ = Task.Run(async () =>
{
using var client = new WebClient();
client.DownloadStringCompleted += (_, args) =>
{
if (args.Cancelled)
{
Console.WriteLine("The download was canceled.");
}
else
{
Console.WriteLine("The download has completed:\n");
Console.WriteLine($"{args.Result}\n\nPress any key to continue.");
}
};
if (!token.IsCancellationRequested)
{
using CancellationTokenRegistration ctr = token.Register(() => client.CancelAsync());
Console.WriteLine("Starting request\n");
await client.DownloadStringTaskAsync(new Uri("http://www.contoso.com"));
}
}, token);
Console.WriteLine("Press 'c' to cancel.\n\n");
if (Console.ReadKey().KeyChar == 'c')
{
cts.Cancel();
}
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
}
Imports System.Net
Imports System.Threading
Friend Class CancelWithCallback
Private Shared Sub Main()
Using cts = New CancellationTokenSource()
Dim token = cts.Token
Task.Run(
Async Function()
Using client As New WebClient()
AddHandler client.DownloadDataCompleted,
Sub(__, args)
If args.Cancelled Then
Console.WriteLine("The download was canceled.")
Else
Console.WriteLine($"The download has completed:{vbLf}")
Console.WriteLine($"{args.Result}{vbLf}{vbLf}Press any key to continue.")
End If
End Sub
If Not token.IsCancellationRequested Then
Dim ctr As CancellationTokenRegistration = token.Register(Sub() client.CancelAsync())
Console.WriteLine($"Starting request{vbLf}")
Await client.DownloadStringTaskAsync(New Uri("http://www.contoso.com"))
End If
End Using
End Function, token)
Console.WriteLine($"Press 'c' to cancel.{vbLf}{vbLf}")
If Console.ReadKey().KeyChar = "c"c Then
cts.Cancel()
End If
Console.WriteLine($"{vbLf}Press any key to exit.")
Console.ReadKey()
End Using
End Sub
End Class
如果注册回调时已经请求了取消,那么仍然要保证调用回调。 在此特定情况下,如果当前未执行异步操作,则 CancelAsync 方法将不进行任何操作,因此调用此方法始终是安全的。
请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈