public async void AddStationToRefreshingPool(Station station) { if (!station.Loaded) { var contract = station.Contract; if (contract != null) { if (await contract.RefreshAsync(station).ConfigureAwait(false)) { if (station.IsUiRefreshNeeded) { StationRefreshed?.Invoke(station, EventArgs.Empty); } } if (contract.ImageAvailability) { station.IsInRefreshPool = true; refreshingPool.Add(station); if (!IsStationWorkerRunning) { StartRefreshStationsAsync(); } } } } }
private async void StartRefreshStationsAsync() { IsStationWorkerRunning = true; while (refreshingPool.Count > 0) { await Task.Delay(15000).ConfigureAwait(false); if (CrossConnectivity.Current.IsConnected) { BatchBlock <Station> batchBlock = new BatchBlock <Station>(5); var actionBlock = new ActionBlock <Station[]>( async stations => { foreach (var station in stations) { if (await station.Contract.RefreshAsync(station)) { if (station.IsUiRefreshNeeded) { StationRefreshed?.Invoke(station, EventArgs.Empty); } } } }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 5 }); batchBlock.LinkTo(actionBlock, new DataflowLinkOptions { PropagateCompletion = true }); foreach (var station in refreshingPool) { await batchBlock.SendAsync(station); // wait synchronously for the block to accept. } batchBlock.Complete(); actionBlock.Completion.Wait(15000); } } IsStationWorkerRunning = false; }