using System; using System.Threading; using System.Threading.Tasks; using Windows.UI.Core; using Windows.UI.Xaml.Media; namespace MapControl { public partial class TileImageLoader { private static async Task LoadTileImage(Tile tile, Func> loadImageFunc, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource(); async void LoadTileImage() { try { var image = await loadImageFunc(); if (cancellationToken.IsCancellationRequested) { tile.IsPending = true; tcs.TrySetCanceled(cancellationToken); } else { tile.SetImageSource(image); tcs.TrySetResult(null); } } catch (Exception ex) { tcs.TrySetException(ex); } } if (!await tile.Image.Dispatcher.TryRunAsync(CoreDispatcherPriority.Low, LoadTileImage)) { tcs.TrySetCanceled(CancellationToken.None); } await tcs.Task; } } }