void PlayGif(FFGifDrawable gifDrawable, CancellationTokenSource tokenSource) { var token = tokenSource.Token; Task.Run(async() => { try { token.ThrowIfCancellationRequested(); var gifDecoder = gifDrawable.GifHelper; int n = gifDecoder.GetFrameCount(); //int ntimes = gifDecoder.GetLoopCount(); //TODO DISABLED for endless loop int ntimes = 0; int repetitionCounter = 0; do { for (int i = 0; i < n; i++) { token.ThrowIfCancellationRequested(); var bitmap = gifDecoder.GetFrame(i); int t = gifDecoder.GetDelay(i); if (bitmap != null && bitmap.Handle != IntPtr.Zero && !bitmap.IsRecycled) { await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(() => base.SetImageBitmap(bitmap)).ConfigureAwait(false); } token.ThrowIfCancellationRequested(); await Delay.DelayAsync(t - 2); } if (ntimes != 0) { repetitionCounter++; } } while (repetitionCounter <= ntimes); } catch (Exception) { } finally { tokenSource.TryDispose(); } }, token); }