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
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();
}
}
}