protected virtual void OnStop(EventArgs e) { OnStopListening?.Invoke(); }
private async void DoStartListening(object o) { PipeWriter writer = null; CancellationToken ct; UdpClient udpClient = null; Exception exception = null; try { (writer, ct) = (ValueTuple <PipeWriter, CancellationToken>)o; writer.OnReaderCompleted((ex, oo) => { exception = ex; _listening = false; }, null); using (udpClient = new UdpClient(Port)) { _timer = new Timer(uc => { if (!_listening || ct.IsCancellationRequested) { ((UdpClient)uc)?.Close(); _timer?.Dispose(); } }, udpClient, 1000, 1000); while (_listening && !ct.IsCancellationRequested) { var result = await udpClient.ReceiveAsync(); var buffer = result.Buffer; if (buffer.Length == 0) { continue; } if (!PacketParser.ValidatePacketHeaderAndLength(buffer)) { continue; } await writer.WriteAsync(buffer, _cts.Token); } } } catch (Exception ex) { Logger.Error("Exception occured while receiving data from network", ex); exception = ex; } finally { if (exception != null) { Logger.Warn("Finished writing because reader completed with exception", exception); } _timer?.Dispose(); writer?.Complete(); udpClient?.Close(); _listening = false; } OnStopListening?.Invoke(this, exception); }