在ASP Net Core服务中在哪里运行异步方法

时间:2018-06-25 20:24:56

标签: asynchronous .net-core

我有一个Service,它必须保持与数据库的实时连接。必须在任何客户端请求之前实例化此连接。

由于Database API提供了一种用于连接到它的异步方法,因此在发出任何请求之前我可以在哪里连接到数据库?

SocketMiddleware

class SocketMiddleware
    {
        Handler handler;
        public SocketMiddleware(Handler _handler,RequestDelegate del)
        {
            this.handler = _handler;
            this.next = del;
        }

        RequestDelegate next;

        public async Task Invoke(HttpContext context)
        {

            if (!context.WebSockets.IsWebSocketRequest)
            {
                await  this.next(context);
                return;
            }
            await this.handler.AddClientAsync(context.WebSockets);

        }
    }
使用实时RethinkDB连接的

服务

 class Handler
        {

            private readonly RethinkDB r;
            public  Connection Con { get; private set; }

            private ConcurrentDictionary<string, Client> clients = new ConcurrentDictionary<string, Client>();
            private object Lock = new object();

            public Handler()
            {
                this.r = new RethinkDB();
               //I have to instnatiate --- this.Con = this.r.Connection().Port(Constants.RETHINK_PORT).Hostname(Constants.HOST_NAME).ConnectAsync();
            }
              ///////////////////////////---Where can i run the below method?
            public async Task ConnectRethinkAsync()
            {
                using (Process proc = new Process())
                {
                    proc.StartInfo = new ProcessStartInfo(Constants.RETHINK_PROCESS_PATH);
                    proc.Start();


                    this.Con = await this.r.Connection().Port(Constants.RETHINK_PORT).Hostname(Constants.HOST_NAME).ConnectAsync();
                }

            }
            public async Task AddClientAsync(WebSocketManager manager)
            {
                WebSocket clientSocket = await manager.AcceptWebSocketAsync();
                string clientID = Ext.MakeId();
                using (Client newClient = Client.Create(clientSocket, clientID))
                {

                    while (true)
                    {
                        if (!newClient.KeepAlive)
                        {
                            break;
                        }
                        ReadOnlyMemory<byte>received = await newClient.ReceiveAsync();
                        string toSend =  $"From Server:\r\nDate:{DateTime.Now.ToString()},WasReceived:{Encoding.UTF8.GetString(received.ToArray())}\r\nEnd of Message\r\n";
                       // await r.Db(Constants.DB_NAME).Table(Constants.TABLE_NAME).RunAsync(this.Con);
                        await newClient.SendAsync(toSend);
                    }
                }



            }
            public bool RemoveClient(string ID)
            {
                if (this.clients.TryRemove(ID, out Client value))
                {
                    value.Dispose();
                    return true;
                }
                return false;

            }

        }

PS:在以上代码段中,最重要的一行是带有注释的行:我需要实例化 Connection ,这是一个异步操作。
我无法在Handler ctor,也不能在SocketMiddleware ctor中使用。
Con必须在执行任何请求之前初始化。(在我们的示例中,调用AddClientAsync) 数据库连接应该在其他服务中完成吗?

1 个答案:

答案 0 :(得分:0)

由于您已经保护了要从外部设置的连接,因此可以在AddClientAsync中实例化连接,例如:

if(this.Con == null)
{
    this.Con = await this.r.Connection()
           .Port(Constants.RETHINK_PORT)
           .Hostname(Constants.HOST_NAME)
           .ConnectAsync();
}