1 // OpenTween - Client of Twitter
2 // Copyright (c) 2013 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
3 // All rights reserved.
5 // This file is part of OpenTween.
7 // This program is free software; you can redistribute it and/or modify it
8 // under the terms of the GNU General Public License as published by the Free
9 // Software Foundation; either version 3 of the License, or (at your option)
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 // You should have received a copy of the GNU General Public License along
18 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
19 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
20 // Boston, MA 02110-1301, USA.
23 using System.Collections.Generic;
26 using System.Threading.Tasks;
28 using System.Threading;
29 using System.Xml.Serialization;
30 using System.Net.Http;
34 public class ImageCache : IDisposable
37 /// 画像の取得に使用する HttpClient インスタンス
39 private readonly HttpClient http;
42 /// キャッシュとして URL と取得した画像を対に保持する辞書
44 internal LRUCacheDictionary<string, Task<MemoryImage>> innerDictionary;
47 /// 非同期タスクをキャンセルするためのトークンのもと
49 private CancellationTokenSource cancelTokenSource;
52 /// innerDictionary の排他制御のためのロックオブジェクト
54 private object lockObject = new object();
59 private bool disposed = false;
61 public ImageCache(HttpClient http)
65 this.innerDictionary = new LRUCacheDictionary<string, Task<MemoryImage>>(trimLimit: 300, autoTrimCount: 100);
66 this.innerDictionary.CacheRemoved += (s, e) => {
67 // まだ参照されている場合もあるのでDisposeはファイナライザ任せ
68 this.CacheRemoveCount++;
71 this.cancelTokenSource = new CancellationTokenSource();
77 public long CacheCount
79 get { return this.innerDictionary.Count; }
85 public int CacheRemoveCount { get; private set; }
88 /// 指定された URL にある画像を非同期に取得するメソッド
90 /// <param name="address">取得先の URL</param>
91 /// <param name="force">キャッシュを使用せずに取得する場合は true</param>
92 /// <returns>非同期に画像を取得するタスク</returns>
93 public Task<MemoryImage> DownloadImageAsync(string address, bool force = false)
95 var cancelToken = this.cancelTokenSource.Token;
99 Task<MemoryImage> cachedImageTask = null;
100 lock (this.lockObject)
102 innerDictionary.TryGetValue(address, out cachedImageTask);
104 if (cachedImageTask != null)
108 this.innerDictionary.Remove(address);
110 if (cachedImageTask.Status == TaskStatus.RanToCompletion)
111 cachedImageTask.Result.Dispose();
113 cachedImageTask.Dispose();
114 cachedImageTask = null;
117 return cachedImageTask;
120 cancelToken.ThrowIfCancellationRequested();
122 var imageTask = this.FetchImageAsync(address, cancelToken);
123 this.innerDictionary[address] = imageTask;
130 private async Task<MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
132 using (var response = await this.http.GetAsync(uri, cancelToken).ConfigureAwait(false))
134 var imageStream = await response.Content.ReadAsStreamAsync()
135 .ConfigureAwait(false);
137 return await MemoryImage.CopyFromStreamAsync(imageStream)
138 .ConfigureAwait(false);
142 public MemoryImage TryGetFromCache(string address)
144 lock (this.lockObject)
146 Task<MemoryImage> imageTask;
147 if (!this.innerDictionary.TryGetValue(address, out imageTask) ||
148 imageTask.Status != TaskStatus.RanToCompletion)
151 return imageTask.Result;
155 public void CancelAsync()
157 lock (this.lockObject)
159 var oldTokenSource = this.cancelTokenSource;
160 this.cancelTokenSource = new CancellationTokenSource();
162 oldTokenSource.Cancel();
163 oldTokenSource.Dispose();
167 protected virtual void Dispose(bool disposing)
169 if (this.disposed) return;
175 lock (this.lockObject)
177 foreach (var item in this.innerDictionary)
179 var task = item.Value;
180 if (task.Status == TaskStatus.RanToCompletion && task.Result != null)
181 task.Result.Dispose();
184 this.innerDictionary.Clear();
185 this.cancelTokenSource.Dispose();
189 this.disposed = true;
192 public void Dispose()
195 GC.SuppressFinalize(this);