public async Task <List <MarketCoin> > GetAllCoinsMarketDetailsAPI() { if (_memoryCache.TryGetValue(Constant.Session.GlobalAllCoinsAPIData, out MarketFetchData marketData)) { if (marketData.LastUpdated.AddSeconds(45) < DateTime.Now) // Update/Refresh Data { if (marketData.CurrentlyUpdating && marketData.LastUpdated.AddMinutes(3) > DateTime.Now) // It's already updating & less than 3 minutes has passed since API call { // Just wait for it to get automatically get updated in the threadpool. Return outdated data for now. return(marketData.MarketCoins); } // Data is outdated & It's not updating yet || It's trying to update, it's been over 3 minutes, still nothing. Retry again. API Server is slow/down. if (!marketData.CurrentlyUpdating) { marketData.CurrentlyUpdating = true; _memoryCache.Set(Constant.Session.GlobalAllCoinsAPIData, marketData, TimeSpan.FromHours(1)); } ThreadPool.QueueUserWorkItem(delegate { // Start an update process in the background. MarketFetchData data = new MarketFetchData { MarketCoins = FetchAPILogic.GetAllCoinsFromApiAsync().Result, LastUpdated = DateTime.Now }; if (!data.MarketCoins.IsNullOrEmpty()) { _memoryCache.Set(Constant.Session.GlobalAllCoinsAPIData, data, TimeSpan.FromHours(1)); } }); } // Fresh data return(marketData.MarketCoins); } List <MarketCoin> fetchedCoins = await FetchAPILogic.GetAllCoinsFromApiAsync(); MarketFetchData newData = new MarketFetchData { MarketCoins = fetchedCoins, LastUpdated = DateTime.Now }; _memoryCache.Set(Constant.Session.GlobalAllCoinsAPIData, newData, TimeSpan.FromHours(1)); return(newData.MarketCoins); }
//[TestMethod] public void RefreshOfficialCoinsInDB() { List <LocalCoins.MarketCoin> fetchedCoins = FetchAPILogic.GetAllCoinsFromApiAsync().Result; using (PegasunDBContext db = new PegasunDBContext()) { List <OfficialCoins> existingOfficialCoins = db.OfficialCoins.ToList(); fetchedCoins.ForEach(x => { if (!existingOfficialCoins.Any(o => o.Name == x.CoinMarketCapID)) { db.OfficialCoins.Add(new OfficialCoins { Name = x.CoinMarketCapID, Symbol = x.Symbol }); } }); db.SaveChanges(); } }