private void OnVisibilityChanged(object sender, VisibilityChangedEventArgs e) { if (e.Visible) { _imageDecoder?.Start(); } else if (!e.Visible) { _imageDecoder?.Stop(); // Prevent unnecessary work } }
private async Task <ImageSource> LoadImageByUri(Uri uriSource, CancellationTokenSource cancellationTokenSource) { var randStream = await this.CurrentLoader.LoadImageStream(uriSource, cancellationTokenSource); if (randStream == null) { throw new Exception("stream is null"); } ImageSource imageSource = null; bool hasDecoder = false; //debug模式不允许Decoders,直接采用默认方案 if (!DesignMode.DesignModeEnabled) { var decoders = this.CurrentLoader.GetAvailableDecoders(); if (decoders.Count > 0) { int maxHeaderSize = decoders.Max(x => x.HeaderSize); if (maxHeaderSize > 0) { byte[] header = new byte[maxHeaderSize]; var readStream = randStream.AsStreamForRead(); readStream.Position = 0; await readStream.ReadAsync(header, 0, maxHeaderSize); readStream.Position = 0; var decoder = decoders.FirstOrDefault(x => x.IsSupportedFileFormat(header)); if (decoder != null) { var source = await decoder.InitializeAsync(this.Dispatcher, randStream, cancellationTokenSource); imageSource = source.ImageSource; this.PixelHeight = source.PixelHeight; this.PixelWidth = source.PixelWidth; if (!cancellationTokenSource.IsCancellationRequested) { _imageDecoder?.Dispose(); Interlocked.Exchange(ref _imageDecoder, decoder); if (_isControlLoaded) { _imageDecoder.Start(); } } hasDecoder = true; } } } } if (!hasDecoder) { var bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(randStream).AsTask(cancellationTokenSource.Token); this.PixelHeight = bitmapImage.PixelHeight; this.PixelWidth = bitmapImage.PixelWidth; imageSource = bitmapImage; } return(imageSource); }