简体   繁体   English

gRPC 服务器上的任务参数范围

[英]Task parameter scope on gRPC server

I have a gRPC server Task that gets called from clients.我有一个从客户端调用的 gRPC 服务器任务。 The request parameter is scoped in the Task and i dont know how to retrieve it and use it in other classes.请求参数在任务范围内,我不知道如何检索它并在其他类中使用它。 printing "currentRequest" outside of the task returns nothing.在任务外打印“currentRequest”不返回任何内容。 Thank you so much for your help.非常感谢你的帮助。

public class LoggingImpl : Logging.LoggingBase
{
    private Server server;
    RequestInfo currentRequest;
    public ClientController controller;

    public override Task<LoggingResponse> LoggingMCM(RequestInfo request, ServerCallContext context)
    {
        currentRequest = request;
        Console.Log(currentRequest);
        return Task.FromResult(new LoggingResponse { Result = "this is a reply from Unity Server" });
    }

    public void GetRequestInfo()
    {
        Console.Log(currentRequest);
    }


    public void StartServer()
    {
        server = new Server
        {
            Services = { Logging.BindService(new LoggingImpl()) },
            Ports = { new ServerPort("127.0.0.1", 50010, ServerCredentials.Insecure) }

        };
        server.Start();
    }
}

I was expecting the currentRequest to be usable outside of the Taks scope.我期望 currentRequest 可以在 Taks 范围之外使用。 How would one use the request info on the main thread and other classes?如何在主线程和其他类上使用请求信息?

Since gRPC services are registered as transient (at least if they are registered the standard way), a new instance of your class LogginImpl will be created for each gRPC call to the service.由于gRPC 服务注册为瞬态(至少如果它们以标准方式注册),将为每次 gRPC 服务调用创建类LogginImpl的新实例。

Making the request static could result in the behaviour you expect, since it will not be re-instantiated with each call (in line 4):使请求静态化可能会导致您期望的行为,因为它不会在每次调用时重新实例化(第 4 行):

private static RequestInfo currentRequest;

Keep in mind, if you want log a (string) message from the request, you still have to extract the message from the request (since you pass the whole object to the Console in the GetRequestInfo() method)请记住,如果您想从请求中记录一条(字符串)消息,您仍然必须从请求中提取消息(因为您在GetRequestInfo()方法中将整个对象传递给了控制台)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM