public async Task StartDiscoveringAsync() { var runningTask = Task.Run(async () => { await Task.Delay(TimeSpan.MaxValue, _cancellationToken.Token).ContinueWith(_ => { }); }); await Task.Delay(TimeSpan.FromSeconds(5), _cancellationToken.Token).ContinueWith(_ => { }); using (var deviceLocator = new SsdpDeviceLocator()) { deviceLocator.StartListeningForNotifications(); deviceLocator.DeviceAvailable += async (s, e) => { await UpnpDeviceFound(e.DiscoveredDevice); }; while (!_cancellationToken.IsCancellationRequested) { Task<IEnumerable<DiscoveredSsdpDevice>> searchTask; try { searchTask = deviceLocator.SearchAsync("upnp:rootdevice", TimeSpan.FromSeconds(10)); await Task.WhenAny(runningTask, searchTask); } catch (Exception e) { _log.Error(e.Message, e); continue; } if (_cancellationToken.IsCancellationRequested) { break; } var devices = searchTask.Result; if (devices == null) { continue; } foreach (var device in devices) { await UpnpDeviceFound(device); } await Task.Delay(TimeSpan.FromSeconds(60), _cancellationToken.Token).ContinueWith(_ => { }); } } }