XAML-Map-Control/MapControl/WPF/TileImageLoader.WPF.cs

61 lines
2.2 KiB
C#
Raw Normal View History

2017-08-04 21:38:58 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2023-01-03 15:12:53 +01:00
// Copyright © 2023 Clemens Fischer
2017-08-04 21:38:58 +02:00
// Licensed under the Microsoft Public License (Ms-PL)
using System;
using System.IO;
using System.Runtime.Caching;
using System.Threading.Tasks;
2022-11-20 18:51:59 +01:00
using System.Windows.Media;
2017-08-04 21:38:58 +02:00
namespace MapControl
{
public partial class TileImageLoader
2017-08-04 21:38:58 +02:00
{
/// <summary>
/// Default folder path where an ObjectCache instance may save cached data, i.e. C:\ProgramData\MapControl\TileCache
2017-08-04 21:38:58 +02:00
/// </summary>
2022-08-06 10:40:59 +02:00
public static string DefaultCacheFolder =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MapControl", "TileCache");
2017-08-04 21:38:58 +02:00
/// <summary>
2021-07-02 21:30:38 +02:00
/// An ObjectCache instance used to cache tile image data. The default value is MemoryCache.Default.
2017-08-04 21:38:58 +02:00
/// </summary>
public static ObjectCache Cache { get; set; } = MemoryCache.Default;
2021-11-22 23:07:07 +01:00
private static async Task LoadCachedTile(Tile tile, Uri uri, string cacheKey)
2017-08-04 21:38:58 +02:00
{
2021-07-02 15:57:01 +02:00
var cacheItem = Cache.Get(cacheKey) as Tuple<byte[], DateTime>;
var buffer = cacheItem?.Item1;
2021-07-02 15:57:01 +02:00
if (cacheItem == null || cacheItem.Item2 < DateTime.UtcNow)
2017-08-04 21:38:58 +02:00
{
2020-09-25 15:02:41 +02:00
var response = await ImageLoader.GetHttpResponseAsync(uri).ConfigureAwait(false);
if (response != null) // download succeeded
{
2021-07-02 15:57:01 +02:00
buffer = response.Buffer; // may be null or empty when no tile available, but still be cached
2021-07-02 15:57:01 +02:00
cacheItem = Tuple.Create(buffer, GetExpiration(response.MaxAge));
2021-06-30 17:56:02 +02:00
2021-07-02 15:57:01 +02:00
Cache.Set(cacheKey, cacheItem, new CacheItemPolicy { AbsoluteExpiration = cacheItem.Item2 });
2017-08-04 21:38:58 +02:00
}
}
//else System.Diagnostics.Debug.WriteLine($"Cached: {cacheKey}");
2017-08-04 21:38:58 +02:00
if (buffer != null && buffer.Length > 0)
2017-08-04 21:38:58 +02:00
{
2022-11-20 18:51:59 +01:00
await LoadTile(tile, () => ImageLoader.LoadImageAsync(buffer));
2017-08-04 21:38:58 +02:00
}
}
2022-11-20 18:51:59 +01:00
private static async Task LoadTile(Tile tile, Func<Task<ImageSource>> loadImageFunc)
{
2022-11-20 18:51:59 +01:00
var image = await loadImageFunc().ConfigureAwait(false);
2022-11-17 23:11:40 +01:00
await tile.Image.Dispatcher.InvokeAsync(() => tile.SetImageSource(image));
2017-08-04 21:38:58 +02:00
}
}
}