private async Task <bool> StopWebHost() { if (this.webHost != null) { try { await this.webHost.StopAsync(TimeSpan.FromSeconds(1)).ConfigureAwait(false); } catch (Exception e) { logger.Error("Unhandled exception while stopping the web host instance.", e); } finally { this.webHost = null; } return(true); } return(false); }
public async Task StartAsync(bool restart) { bool messageThreadNeededToBeStopped = false; bool socketNeededToBeClosed = false; bool webHostNeededToBeStopped = false; if (restart || this.Port != this.webHost?.Uri.Port) { messageThreadNeededToBeStopped = this.StopReceiveMessageThread(); socketNeededToBeClosed = await this.CloseSocket((WebSocketCloseStatus)1012).ConfigureAwait(false); webHostNeededToBeStopped = await this.StopWebHost().ConfigureAwait(false); } // Create a new web host and start it if (this.webHost == null) { this.webHost = new KestrelWebSocketHost <ToastifyWebSocketHostStartup>($"http://localhost:{this.Port}"); try { this.webHost.Start(); } catch (Exception e) { if (e.Message.Contains("EADDRINUSE")) { this.Port = (uint)GetFreeTcpPort(); this.webHost = new KestrelWebSocketHost <ToastifyWebSocketHostStartup>($"http://localhost:{this.Port}"); this.webHost.Start(); } else { this.webHost = null; logger.Error("Unhandled exception while starting the web host.", e); } } // Create a new internal socket if (this.webHost != null && this.socket == null) { this.socket = new ClientWebSocket(); if (messageThreadNeededToBeStopped || socketNeededToBeClosed || webHostNeededToBeStopped) { logger.Debug($"{nameof(ToastifyBroadcaster)} restarted!"); } else { logger.Debug($"{nameof(ToastifyBroadcaster)} started!"); } } } this.cts?.Dispose(); this.cts = new CancellationTokenSource(); if (this.webHost != null) { this.receiveMessageThread = ThreadManager.Instance.CreateThread(this.ReceiveMessageLoop); this.receiveMessageThread.IsBackground = true; this.receiveMessageThread.Name = $"{nameof(ToastifyBroadcaster)}_ReceiveMessageThread"; this.receiveMessageThread.Start(); } }