private void Application_ApplicationExit(object sender, EventArgs e) { HostApplicationLifetime.StopApplication(); if (!_shutdownBlock.WaitOne(TimeSpan.FromSeconds(5))) { Logger.LogInformation("Waiting for the host to be disposed. Ensure all 'IHost' instances are wrapped in 'using' blocks."); } _shutdownBlock.WaitOne(); // On Linux if the shutdown is triggered by SIGTERM then that's signaled with the 143 exit code. // Suppress that since we shut down gracefully. https://github.com/dotnet/aspnetcore/issues/6526 System.Environment.ExitCode = 0; }
private async Task RunAsync() { try { var address = BindingAddress.Parse(Options.Url); if (!IPAddress.TryParse(address.Host, out var ip)) { ip = Dns.GetHostEntry(address.Host).AddressList.First(); } var endpoint = new IPEndPoint(ip, address.Port); _logger.LogInformation($"Connecting to '{endpoint}'."); await using var context = await _connectionFactory.ConnectAsync(endpoint); _logger.LogInformation($"Connected to '{endpoint}'."); var originalTransport = context.Transport; IAsyncDisposable sslState = null; if (address.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) { _logger.LogInformation("Starting TLS handshake."); var memoryPool = context.Features.Get <IMemoryPoolFeature>()?.MemoryPool; var inputPipeOptions = new StreamPipeReaderOptions(memoryPool, memoryPool.GetMinimumSegmentSize(), memoryPool.GetMinimumAllocSize(), leaveOpen: true); var outputPipeOptions = new StreamPipeWriterOptions(pool: memoryPool, leaveOpen: true); var sslDuplexPipe = new SslDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions); var sslStream = sslDuplexPipe.Stream; sslState = sslDuplexPipe; context.Transport = sslDuplexPipe; await sslStream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = address.Host, RemoteCertificateValidationCallback = (_, __, ___, ____) => true, ApplicationProtocols = new List <SslApplicationProtocol> { SslApplicationProtocol.Http2 }, EnabledSslProtocols = SslProtocols.Tls12, }, CancellationToken.None); _logger.LogInformation($"TLS handshake completed successfully."); } var http2Utilities = new Http2Utilities(context, _logger, _stopTokenSource.Token); try { await Options.Scenaro(http2Utilities); } catch (Exception ex) { _logger.LogError(ex, "App error"); throw; } finally { // Unwind Https for shutdown. This must happen before the context goes out of scope or else DisposeAsync will never complete context.Transport = originalTransport; if (sslState != null) { await sslState.DisposeAsync(); } } } finally { HostApplicationLifetime.StopApplication(); } }
private void Desktop_Exit(object sender, ControlledApplicationLifetimeExitEventArgs e) { HostApplicationLifetime.StopApplication(); }
async Task InputLineLoopAsync(string inputLine) { int checkpointnumber = 0; // check CancellationToken to see if this task is canceled CheckAndHandleCancellationToken(checkpointnumber++); logger.LogDebug(uiLocalizer["{0} {1} inputLineString = {2}", "StdInHandlerService", "InputLineLoopAsync", inputLine]); // Echo to stdOut the line that came in on stdIn serviceData.Mesg.Append(uiLocalizer["You selected: {0}", inputLine]); #region Write the mesg to stdout using (Task task = await WriteMessageSafelyAsync().ConfigureAwait(false)) { if (!task.IsCompletedSuccessfully) { if (task.IsCanceled) { // Ignore if user cancelled the operation during output to stdout (internal cancellation) // re-throw if the cancellation request came from outside the stdInLineMonitorAction /// ToDo: evaluate the linked, inner, and external tokens throw new OperationCanceledException(); } else if (task.IsFaulted) { //ToDo: Go through the inner exception //foreach (var e in t.Exception) { // https://docs.microsoft.com/en-us/dotnet/standard/io/handling-io-errors // ToDo figure out what to do if the output stream is closed throw new Exception("ToDo: WriteMessageSafelyAsync returned an AggregateException"); //} } } serviceData.Mesg.Clear(); } #endregion #region Switch on user's selection switch (inputLine) { case "1": // switch stdIn process to FileSystemToObjectGraphService FileSystemToObjectGraphService.EnableListeningToStdInAsync(FinishedWithStdInAction); serviceData.SubscriptionToConsoleReadLineAsyncAsObservableDisposeHandle.Dispose(); break; case "2": // switch stdIn process to FileSystemGraphToDBService FileSystemGraphToDBService.EnableListeningToStdInAsync(FinishedWithStdInAction); serviceData.SubscriptionToConsoleReadLineAsyncAsObservableDisposeHandle.Dispose(); break; case "99": #region Quit the program // an instance of IHostApplicationLifetime is constructor-injected primarly to provide access to its StopApplication method HostApplicationLifetime.StopApplication(); #endregion break; default: //serviceData.Mesg.Clear(); serviceData.Mesg.Append(uiLocalizer["InvalidInput Does Not Match Available Choices: {0}", inputLine]); Task.Delay(100000); break; } #endregion #region Write the mesg to stdout using (Task task = await WriteMessageSafelyAsync().ConfigureAwait(false)) { if (!task.IsCompletedSuccessfully) { if (task.IsCanceled) { // Ignore if user cancelled the operation during output to stdout (internal cancellation) // re-throw if the cancellation request came from outside the stdInLineMonitorAction /// ToDo: evaluate the linked, inner, and external tokens throw new OperationCanceledException(); } else if (task.IsFaulted) { //ToDo: Go through the inner exception //foreach (var e in t.Exception) { // https://docs.microsoft.com/en-us/dotnet/standard/io/handling-io-errors // ToDo figure out what to do if the output stream is closed throw new Exception("ToDo: WriteMessageSafelyAsync returned an AggregateException"); //} } } serviceData.Mesg.Clear(); } #endregion #region Build and Display menu await BuildAndDisplayMenu(); #endregion #region Write the mesg to stdout using (Task task = await WriteMessageSafelyAsync().ConfigureAwait(false)) { if (!task.IsCompletedSuccessfully) { if (task.IsCanceled) { // Ignore if user cancelled the operation during output to stdout (internal cancellation) // re-throw if the cancellation request came from outside the stdInLineMonitorAction /// ToDo: evaluate the linked, inner, and external tokens throw new OperationCanceledException(); } else if (task.IsFaulted) { //ToDo: Go through the inner exception //foreach (var e in t.Exception) { // https://docs.microsoft.com/en-us/dotnet/standard/io/handling-io-errors // ToDo figure out what to do if the output stream is closed throw new Exception("ToDo: WriteMessageSafelyAsync returned an AggregateException"); //} } } serviceData.Mesg.Clear(); } #endregion }