C#中Task.ContinueWith如何使用
Task.ContinueWith
方法是 Task
类的一个成员,它允许你为一个任务添加一个延续操作。这个延续操作会在任务完成时执行,无论是成功完成、发生异常还是被取消。你可以使用这个方法来执行一些清理工作,或者基于前一个任务的结果来启动另一个任务。
以下是 Task.ContinueWith
方法的一些常见用法:
基本用法
Task task = Task.Run(() =>
{
// 执行一些工作
return "Hello from Task";
});
// 添加一个延续操作,当任务完成时执行
task.ContinueWith(antecedent =>
{
// antecedent 是前一个任务,即 task
string result = antecedent.Result; // 获取前一个任务的结果
Console.WriteLine(result);
});
处理异常
Task task = Task.Run(() =>
{
throw new Exception("Something went wrong");
});
task.ContinueWith(antecedent =>
{
if (antecedent.IsFaulted)
{
// antecedent.Exception 包含异常信息
Console.WriteLine(antecedent.Exception.Flatten().InnerException.Message);
}
});
处理任务取消
CancellationTokenSource cts = new CancellationTokenSource();
Task task = Task.Run(() =>
{
// 模拟长时间运行的任务
Thread.Sleep(5000);
}, cts.Token);
// 取消任务
cts.Cancel();
task.ContinueWith(antecedent =>
{
if (antecedent.IsCanceled)
{
Console.WriteLine("Task was canceled.");
}
});
使用任务结果启动另一个任务
Task<string> task = Task.Run(() => "Hello");
task.ContinueWith(antecedent =>
{
string input = antecedent.Result;
return input.ToUpper(); // 将结果转换为大写
}).ContinueWith(antecedent =>
{
Console.WriteLine(antecedent.Result); // 输出 "HELLO"
});
指定任务完成的状态
ContinueWith
方法允许你指定在哪些状态下执行延续操作:
task.ContinueWith(antecedent =>
{
// 这个延续操作只会在任务成功完成时执行
Console.WriteLine("Task completed successfully.");
}, TaskContinuationOptions.OnlyOnRanToCompletion);
指定延续任务的执行方式
你还可以指定延续任务的执行方式,比如是否应该在同一个线程上执行:
task.ContinueWith(antecedent =>
{
// 这个延续操作会在不同的线程上执行
Console.WriteLine("Continuation running on a different thread.");
}, TaskContinuationOptions.ExecuteSynchronously);
ContinueWith
方法非常灵活,可以根据你的需要来处理任务完成后的各种情况。记住,延续操作默认情况下是在任务调度器上异步执行的,除非你使用了 TaskContinuationOptions.ExecuteSynchronously
选项。
原文地址:https://blog.csdn.net/weixin_64532720/article/details/142924798
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!