public async Task OpenAsync(string host, int port) { try { await Task.Run(() => { this.channel = new Channel($"{host}:{port}", ChannelCredentials.Insecure); this.adaptorImpl = new AdaptorClientImpl(this.channel, Guid.NewGuid(), this.serviceHosts.ToArray()); }); await this.adaptorImpl.OpenAsync(); this.descriptor = await this.instanceContext.CreateInstanceAsync(this.adaptorImpl); await Task.Run(() => { this.cancellation = new CancellationTokenSource(); this.serializer = this.serviceContext.GetService(typeof(ISerializer)) as ISerializer; }); this.task = this.PollAsync(this.cancellation.Token); } catch { if (this.channel != null) { await this.channel.ShutdownAsync(); this.channel = null; } throw; } }
public async Task CloseAsync(int closeCode) { await Task.Run(() => { this.cancellation?.Cancel(); this.cancellation = null; this.task?.Wait(); this.task = null; }); if (this.adaptorImpl != null) { await this.instanceContext.DestroyInstanceAsync(this.adaptorImpl); } if (this.adaptorImpl != null) { await this.adaptorImpl.CloseAsync(); } this.adaptorImpl = null; if (this.channel != null) { await this.channel.ShutdownAsync(); } this.channel = null; }
private async Task PollAsync(CancellationToken cancellationToken) { var closeCode = int.MinValue; try { using var call = this.adaptorImpl.Poll(); while (!cancellationToken.IsCancellationRequested) { var request = new PollRequest() { Token = $"{this.adaptorImpl.Token}" }; await call.RequestStream.WriteAsync(request); await call.ResponseStream.MoveNext(); var reply = call.ResponseStream.Current; if (reply.Code != int.MinValue) { closeCode = reply.Code; break; } this.InvokeCallback(reply.Items); reply.Items.Clear(); await Task.Delay(1); } await call.RequestStream.CompleteAsync(); await call.ResponseStream.MoveNext(); } catch (Exception e) { closeCode = -1; GrpcEnvironment.Logger.Error(e, e.Message); } if (closeCode != int.MinValue) { this.task = null; await this.adaptorImpl.AbortAsync(); this.adaptorImpl = null; this.OnDisconnected(new CloseEventArgs(closeCode)); } }