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;
31 using OpenTween.Connection;
35 public class ImageCache : IDisposable
38 /// キャッシュとして URL と取得した画像を対に保持する辞書
40 internal LRUCacheDictionary<string, Task<MemoryImage>> innerDictionary;
43 /// 非同期タスクをキャンセルするためのトークンのもと
45 private CancellationTokenSource cancelTokenSource;
48 /// innerDictionary の排他制御のためのロックオブジェクト
50 private readonly object lockObject = new object();
55 private bool disposed = false;
59 this.innerDictionary = new LRUCacheDictionary<string, Task<MemoryImage>>(trimLimit: 300, autoTrimCount: 100);
60 this.innerDictionary.CacheRemoved += (s, e) => {
61 // まだ参照されている場合もあるのでDisposeはファイナライザ任せ
62 this.CacheRemoveCount++;
65 this.cancelTokenSource = new CancellationTokenSource();
71 public long CacheCount
72 => this.innerDictionary.Count;
77 public int CacheRemoveCount { get; private set; }
80 /// 指定された URL にある画像を非同期に取得するメソッド
82 /// <param name="address">取得先の URL</param>
83 /// <param name="force">キャッシュを使用せずに取得する場合は true</param>
84 /// <returns>非同期に画像を取得するタスク</returns>
85 public Task<MemoryImage> DownloadImageAsync(string address, bool force = false)
87 var cancelToken = this.cancelTokenSource.Token;
91 lock (this.lockObject)
93 innerDictionary.TryGetValue(address, out var cachedImageTask);
95 if (cachedImageTask != null)
99 this.innerDictionary.Remove(address);
100 cachedImageTask = null;
103 return cachedImageTask;
106 cancelToken.ThrowIfCancellationRequested();
108 var imageTask = this.FetchImageAsync(address, cancelToken);
109 this.innerDictionary[address] = imageTask;
116 private async Task<MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
118 using var response = await Networking.Http.GetAsync(uri, cancelToken)
119 .ConfigureAwait(false);
121 response.EnsureSuccessStatusCode();
123 using var imageStream = await response.Content.ReadAsStreamAsync()
124 .ConfigureAwait(false);
126 return await MemoryImage.CopyFromStreamAsync(imageStream)
127 .ConfigureAwait(false);
130 public MemoryImage TryGetFromCache(string address)
132 lock (this.lockObject)
134 if (!this.innerDictionary.TryGetValue(address, out var imageTask) ||
135 imageTask.Status != TaskStatus.RanToCompletion)
138 return imageTask.Result;
142 public void CancelAsync()
144 lock (this.lockObject)
146 var oldTokenSource = this.cancelTokenSource;
147 this.cancelTokenSource = new CancellationTokenSource();
149 oldTokenSource.Cancel();
150 oldTokenSource.Dispose();
154 protected virtual void Dispose(bool disposing)
156 if (this.disposed) return;
162 lock (this.lockObject)
164 foreach (var (_, task) in this.innerDictionary)
166 if (task.Status == TaskStatus.RanToCompletion)
167 task.Result?.Dispose();
170 this.innerDictionary.Clear();
171 this.cancelTokenSource.Dispose();
175 this.disposed = true;
178 public void Dispose()
181 GC.SuppressFinalize(this);
185 => this.Dispose(false);