rquackenbush / DotNetSigTermTest

Testing responding to SigTerm in a Linux docker container
Apache License 2.0
3 stars 2 forks source link

Use TaskCompletionSource instead CancellationTokenSource #1

Open joseangelmt opened 5 years ago

joseangelmt commented 5 years ago

The call to await Task.Delay(-1, cts.Token) throws and exception of type TaskCancelledException, so the line Console.WriteLine("Exiting..."); is never executed and the program is finalized with the exception.

I think could be a better solution to use TaskCompletionSource instead CancellationTokenSource like this:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace SigTermTest
{
    class Program
    {
        static async Task<int> Main(string[] args)
        {
            var tcs = new TaskCompletionSource<int>();

            AppDomain.CurrentDomain.ProcessExit += (s, e) => 
            {
                Console.WriteLine("ProcessExit!");
                Task.Run(() => tcs.TrySetResult(0));
            };

            Console.WriteLine("Waiting for SIGTERM...");

            await tcs.Task;

            Console.WriteLine("Exiting...");

            return 0;
        }
    }
}
roninttk commented 2 years ago

I was running into the same TaskCancelledException being thrown and crashing the application with "Unhandled exception..." error message. I can confirm this solution does work with the latest .NET 6.0 on Linux. The other solution I had working was wrapping the Task.Delay(-1, cts.Token); call in a try-catch block to handle the exception. Both solutions work.