ContinueWith 是 C# 中 Task 类的一个方法,用于在任务完成后执行另一个任务。它可以处理异步操作的结果,但是需要使用 async/await 语法来处理结果。
下面是一个示例,展示了如何使用 ContinueWith 处理异步操作的结果:
using System; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { await Task.Run(async () => { Console.WriteLine("Start"); await Task.Delay(1000); Console.WriteLine("End"); }).ContinueWith(t => { if (t.IsCompletedSuccessfully) { Console.WriteLine("ContinueWith: Task completed successfully"); Console.WriteLine($"Result: {t.Result}"); } else { Console.WriteLine("ContinueWith: Task failed"); Console.WriteLine($"Exception: {t.Exception}"); } }); Console.ReadKey(); } } 在这个示例中,我们首先创建了一个异步任务,该任务会先输出 “Start”,然后等待 1 秒,最后输出 “End”。接下来,我们使用 ContinueWith 方法来处理这个任务的结果。如果任务成功完成,我们将输出 “ContinueWith: Task completed successfully” 和任务的结果。如果任务失败,我们将输出 “ContinueWith: Task failed” 和异常信息。