/
aprogrammer
/
dotnet-docs
Обзор
Документация
Войти
/
aprogrammer
/
dotnet-docs
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
docs/standard/parallel-programming/snippets/cs/exception2.cs
68 строк
2 KB
David Pine
Address concerns about chaining tasks and lacking continuation examples with .Unwrap() (#19611)
28 июл 2020, 15:00
Не верифицирован
28 июл 2020, 15:00
9685f88
Код
Авторство
О чём код?
// <example> using System; using System.IO; using System.Linq; using System.Threading.Tasks; public class ExceptionTwoExample { public static async Task Main() { var task = Task.Run( () => { string fileText = File.ReadAllText(@"C:\NonexistentFile.txt"); return fileText; }); Task continuation = task.ContinueWith( antecedent => { var fileNotFound = antecedent.Exception ?.InnerExceptions ?.FirstOrDefault(e => e is FileNotFoundException) as FileNotFoundException; if (fileNotFound != null) { Console.WriteLine(fileNotFound.Message); } }, TaskContinuationOptions.OnlyOnFaulted); await continuation; Console.ReadLine(); } } // The example displays the following output: // Could not find file 'C:\NonexistentFile.txt'. // </example> public class Example2 { public static void ShowTaskException() { var task = Task.Run( () => { string fileText = File.ReadAllText(@"C:\NonexistentFile.txt"); return fileText; }); Task continuation = task.ContinueWith( antecedent => { // <exception> var fileNotFound = antecedent.Exception ?.InnerExceptions ?.FirstOrDefault(e => e is FileNotFoundException) as FileNotFoundException; if (fileNotFound != null) { Console.WriteLine(fileNotFound.Message); } // </exception> }, TaskContinuationOptions.OnlyOnFaulted); } }