/// <summary> /// Retrieves item represented by Uri from the in-memory cache if it exists and is not out of date. If item is not found or is out of date, default instance of the generic type is returned. /// </summary> /// <param name="uri">Uri of the item.</param> /// <returns>an instance of Generic type</returns> public T GetFromMemoryCache(Uri uri) { T instance = default(T); string fileName = GetCacheFileName(uri); if (_inMemoryFileStorage.MaxItemCount > 0) { var msi = _inMemoryFileStorage.GetItem(fileName, CacheDuration); if (msi != null) { instance = msi.Item; } } return(instance); }
private async Task <T> GetFromCacheOrDownloadAsync(Uri uri, string fileName, bool preCacheOnly) { StorageFile baseFile = null; T instance = default(T); DateTime expirationDate = DateTime.Now.Subtract(CacheDuration); if (_inMemoryFileStorage.MaxItemCount > 0) { var msi = _inMemoryFileStorage.GetItem(fileName, CacheDuration); if (msi != null) { instance = msi.Item; } } if (instance != null) { return(instance); } var folder = await GetCacheFolderAsync(); baseFile = await folder.TryGetItemAsync(fileName) as StorageFile; if (await IsFileOutOfDate(baseFile, expirationDate)) { baseFile = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); try { instance = await DownloadFileAsync(uri, baseFile, preCacheOnly); } catch (Exception) { await baseFile.DeleteAsync().AsTask().ConfigureAwait(false); throw; // rethrowing the exception changes the stack trace. just throw } } if (EqualityComparer <T> .Default.Equals(instance, default(T)) && !preCacheOnly) { using (var fileStream = await baseFile.OpenAsync(FileAccessMode.Read)) { instance = await InitializeTypeAsync(fileStream); } if (_inMemoryFileStorage.MaxItemCount > 0) { var properties = await baseFile.GetBasicPropertiesAsync().AsTask().ConfigureAwait(false); var msi = new InMemoryStorageItem <T>(fileName, properties.DateModified.DateTime, instance); _inMemoryFileStorage.SetItem(msi); } } return(instance); }