From 8b8af7cb4bd3d9a57ed4ae4d4417bb22689b966e Mon Sep 17 00:00:00 2001 From: Mayuki Sawatari Date: Tue, 14 Jan 2020 10:50:08 +0900 Subject: [PATCH] OperationCanceledException by user code should not be handled. --- sandbox/SingleContainedApp/Program.cs | 22 +++++++++++++++++++-- src/ConsoleAppFramework/ConsoleAppEngine.cs | 6 ++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/sandbox/SingleContainedApp/Program.cs b/sandbox/SingleContainedApp/Program.cs index d5e4dfc..b1818fd 100644 --- a/sandbox/SingleContainedApp/Program.cs +++ b/sandbox/SingleContainedApp/Program.cs @@ -10,6 +10,7 @@ using System.IO; using System.Reflection; using System.Text; +using System.Threading; using System.Threading.Tasks; namespace SingleContainedApp @@ -137,11 +138,28 @@ public class Person public string Name { get; set; } } + + public class ThrowOperationCanceledException : ConsoleAppBase + { + public async Task Throw() + { + //while (true) + //{ + // await Task.Delay(10); + // Context.CancellationToken.ThrowIfCancellationRequested(); + //} + + var cts = new CancellationTokenSource(); + cts.Cancel(); + cts.Token.ThrowIfCancellationRequested(); + } + } + class Program { static async Task Main(string[] args) { - args = new[] { "-array", "10,20,30", "-person", @"{""Age"":10,""Name"":""foo""}" }; + //args = new[] { "-array", "10,20,30", "-person", @"{""Age"":10,""Name"":""foo""}" }; await Host.CreateDefaultBuilder() @@ -149,7 +167,7 @@ await Host.CreateDefaultBuilder() { logging.SetMinimumLevel(LogLevel.Trace).ReplaceToSimpleConsole(); }) - .RunConsoleAppFrameworkAsync(args); + .RunConsoleAppFrameworkAsync(args); // .RunConsoleAppEngineAsync //.ConfigureServices((hostContext, services) => //{ diff --git a/src/ConsoleAppFramework/ConsoleAppEngine.cs b/src/ConsoleAppFramework/ConsoleAppEngine.cs index e6ce84a..3738924 100644 --- a/src/ConsoleAppFramework/ConsoleAppEngine.cs +++ b/src/ConsoleAppFramework/ConsoleAppEngine.cs @@ -164,9 +164,11 @@ async Task RunCore(ConsoleAppContext ctx, Type type, MethodInfo methodInfo, stri } catch (Exception ex) { - if (ex is OperationCanceledException || ex is TaskCanceledException) + if (ex is OperationCanceledException operationCanceledException && operationCanceledException.CancellationToken == cancellationToken) { - return; // do nothing + // NOTE: Do nothing if the exception has thrown by the CancellationToken of ConsoleAppEngine. + // If the user code throws OperationCanceledException, ConsoleAppEngine should not handle that. + return; } if (ex is TargetInvocationException tex)