public Task AddAsync(CachedAlbumArt cache) { return(this.Connection.InsertAsync(cache)); }
public async Task <string> GetCachedImageAsync(Uri url, uint size) { await this.InitializeCacheFolderAsync(); CachedAlbumArt cache = await this.cachedAlbumArtsRepository.FindAsync(url, size); if (cache == null && this.stateService.IsOffline()) { return(null); } if (cache == null) { await this.semaphoreSlim.WaitAsync().ConfigureAwait(continueOnCapturedContext: false); try { var cachedKey = new CachedKey(url, size); cache = await this.downloadTasks.GetOrAdd( cachedKey, uri => Task.Run( async() => { CachedAlbumArt downloadedCache = await this.cachedAlbumArtsRepository.FindAsync(url, size); if (downloadedCache == null) { string fileName = Guid.NewGuid().ToString(); string subFolderName = fileName.Substring(0, 1); var folder = await this.cacheFolder.CreateFolderAsync(subFolderName, CreationCollisionOption.OpenIfExists); var file = await folder.CreateFileAsync(fileName); using (var imageStream = await this.httpClient.GetStreamAsync(url.ChangeSize(size))) { using (var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { using (Stream fileStream = targetStream.AsStreamForWrite()) { await imageStream.CopyToAsync(fileStream); await fileStream.FlushAsync(); } } } downloadedCache = new CachedAlbumArt() { AlbumArtUrl = url, Size = size, FileName = fileName }; await this.cachedAlbumArtsRepository.AddAsync(downloadedCache); } return(downloadedCache); })); Task <CachedAlbumArt> task; this.downloadTasks.TryRemove(cachedKey, out task); } finally { this.semaphoreSlim.Release(1); } } return(Path.Combine(AlbumArtCacheFolder, cache.FileName.Substring(0, 1), cache.FileName)); }