Keep Dotnet Core Grpc Server running as a console application?

后端 未结 2 1437
深忆病人
深忆病人 2021-02-13 14:11

I am trying to keep a Grpc server running as a console daemon. This gRPC server is a microservice that runs in a docker container.

All of the examples I can find make us

2条回答
  •  孤城傲影
    2021-02-13 14:58

    Use ManualResetEvent to block the main thread until you receive a shutdown event.

    For example in a trivial situation:

    class Program
    {
      public static ManualResetEvent Shutdown = new ManualResetEvent(false);
    
      static void Main(string[] args)
      {
        Task.Run(() =>
        {
          Console.WriteLine("Waiting in other thread...");
          Thread.Sleep(2000);
          Shutdown.Set();
        });
    
        Console.WriteLine("Waiting for signal");
        Shutdown.WaitOne();
    
        Console.WriteLine("Resolved");
      }
    }
    

    For example, in your case, I imagine something like:

    using System;
    using System.Net.Sockets;
    using System.Threading;
    using System.Threading.Tasks;
    using Grpc.Core;
    using Helloworld;
    
    namespace GreeterServer
    {
      class GreeterImpl : Greeter.GreeterBase
      {
        // Server side handler of the SayHello RPC
        public override Task SayHello(HelloRequest request, ServerCallContext context)
        {
          Program.Shutdown.Set(); // <--- Signals the main thread to continue 
          return Task.FromResult(new HelloReply {Message = "Hello " + request.Name});
        }
      }
    
      class Program
      {
        const int Port = 50051;
    
        public static ManualResetEvent Shutdown = new ManualResetEvent(false);
    
        public static void Main(string[] args)
        {
          Server server = new Server
          {
            Services = {Greeter.BindService(new GreeterImpl())},
            Ports = {new ServerPort("localhost", Port, ServerCredentials.Insecure)}
          };
          server.Start();
    
          Shutdown.WaitOne(); // <--- Waits for ever or signal received
    
          server.ShutdownAsync().Wait();
        }
      }
    }
    

提交回复
热议问题