保持Dotnet Core Grpc Server作为控制台应用程序运行?
我试图让一个Grpc服务器作为一个控制台守护进程运行。 这个gRPC服务器是一个在Docker容器中运行的微服务。
我可以find的所有例子都使用以下内容:
Console.ReadKey();
这确实阻塞主线程,并保持运行,但在docker中不起作用,出现以下错误:
"Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read."
现在我可以尝试finddocker的解决方法,但这仍然不太合适。 有没有人知道一个好的“生产准备”的方式来保持服务运行?
使用ManualResetEvent
阻塞主线程,直到收到closures事件。
例如,在一个微不足道的情况下:
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"); } }
例如,在你的情况下,我想象一下:
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<HelloReply> 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(); } } }
- 如何在Mac上使用JetBrains Rider开发和debugging运行在Docker中的.NET Core应用程序
- 环境variablesOpenShift .NET Core
- 在Docker中为自己的容器.Net Core应用程序指定运行时
- Docker上的debugging会抛出一个错误
- 在NuGet中debugging.NET Core项目和.NET库
- Docker中用于.NET Core应用程序的appSettings.json?
- 如何检查在PS1中dotnet恢复是否正常?
- Docker .Net核心应用程序,试图连接到SQL数据库
- AWS Codebuild .NET Core构buildDocker镜像