How to write a linux daemon with .Net Core

后端 未结 5 1952
离开以前
离开以前 2021-01-31 05:22

I could just write a long-running CLI app and run it, but I\'m assuming it wouldn\'t comply to all the expectations one would have of a standards-compliant linux daemon (respond

5条回答
  •  再見小時候
    2021-01-31 06:08

    The best I could come up with is based on the answer to two other questions: Killing gracefully a .NET Core daemon running on Linux and Is it possible to await an event instead of another async method?

    using System;
    using System.Runtime.Loader;
    using System.Threading.Tasks;
    
    namespace ConsoleApp1
    {
        public class Program
        {
            private static TaskCompletionSource taskToWait;
    
            public static void Main(string[] args)
            {
                taskToWait = new TaskCompletionSource();
    
                AssemblyLoadContext.Default.Unloading += SigTermEventHandler;
                Console.CancelKeyPress += new ConsoleCancelEventHandler(CancelHandler);
    
                //eventSource.Subscribe(eventSink) or something...
    
                taskToWait.Task.Wait();
    
                AssemblyLoadContext.Default.Unloading -= SigTermEventHandler;
                Console.CancelKeyPress -= new ConsoleCancelEventHandler(CancelHandler);
    
            }
    
    
            private static void SigTermEventHandler(AssemblyLoadContext obj)
            {
                System.Console.WriteLine("Unloading...");
                taskToWait.TrySetResult(null);
            }
    
            private static void CancelHandler(object sender, ConsoleCancelEventArgs e)
            {
                System.Console.WriteLine("Exiting...");
                taskToWait.TrySetResult(null);
            }
    
        }
    }
    
        

    提交回复
    热议问题