c# - 如何确定是否可以使用 CancellationTokenSource 取消某个异步任务?
问题描述
我想知道是否可以使用 CancellationTokenSource 取消任务。如何确定是否可以取消某个异步任务?
public async Task PlayerAccountDetails()
{
CancellationTokenSource cts = new CancellationTokenSource();
try
{
await UpdatePlayerCountryData("Germany", "Berlin");
}
catch (Exception ex)
{
var excep = ex.Message;
}
}
private static async Task UpdatePlayerCountryData(string country, string city)
{
var resultprofile = await PlayFabClientAPI.UpdateUserDataAsync(new PlayFab.ClientModels.UpdateUserDataRequest()
{
Data = new Dictionary<string, string>() {
{"Country", country},
{"City", city}},
Permission = PlayFab.ClientModels.UserDataPermission.Public
});
if (resultprofile.Error != null)
Console.WriteLine(resultprofile.Error.GenerateErrorReport());
else
{
Console.WriteLine("Successfully updated user data");
}
}
解决方案
这是一个实际的例子:
class Program
{
static void Main(string[] args)
{
var cancellationTokenSource = new CancellationTokenSource();
var task = Task.Run(async () => await WatchYourCarBurn(cancellationTokenSource.Token));
Task.Run(async () => await Task.Delay(5000)).Wait();
Console.WriteLine("Too much time elapsed, cancel task.");
cancellationTokenSource.Cancel();
while (!task.IsCompleted && !task.IsCanceled)
{
}
}
private static async Task WatchYourCarBurn(CancellationToken token)
{
Console.WriteLine("You notice some fog");
await Task.Delay(2000);
token.ThrowIfCancellationRequested();
Console.WriteLine("You notice some fire");
await Task.Delay(2000);
token.ThrowIfCancellationRequested();
Console.WriteLine("You notice your car");
await Task.Delay(2000);
token.ThrowIfCancellationRequested();
Console.WriteLine("You notice your car is burning");
await Task.Delay(2000);
token.ThrowIfCancellationRequested();
Console.WriteLine("You watch your car burning");
await Task.Delay(2000);
}
}