异步加载C#中的BitmapImage

1 c# wpf asynchronous

我正在尝试异步加载图像.

MainWindow代码

public partial class MainWindow : Window
{
    private Data data = new Data();
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = data;
    }
    private async void button_Click(object sender, RoutedEventArgs e)
    {
        data.Image = await Data.GetNewImageAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

数据类

public class Data : INotifyPropertyChanged
{
    private BitmapImage _Image = new BitmapImage();
    public BitmapImage Image { get { return _Image; } set { _Image = value; OnPropertyChanged("Image"); } }

    public static BitmapImage GetNewImage()
    {
        return new BitmapImage(new Uri("http://www.diseno-art.com/news_content/wp-content/uploads/2012/09/2013-Jaguar-F-Type-1.jpg"));
    }

    public async static Task<BitmapImage> GetNewImageAsync()
    {
        return await Task.Run(() => GetNewImage());
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
Run Code Online (Sandbox Code Playgroud)

WPF代码

<Button Name="button" Click="button_Click">Image</Button>
<Image Grid.Row="1" Source="{Binding Path=Image, UpdateSourceTrigger=PropertyChanged}"></Image>
Run Code Online (Sandbox Code Playgroud)

问题

我得到了例外:

System.ArgumentException:"必须在与DependencyObject相同的线程上创建DependencySource".

......在这一排: PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

但是如果我将BitmapImage更改为字符串,则此代码可以正常工作.

我究竟做错了什么?

Cle*_*ens 6

在后台线程中创建BitmapImage时,必须确保在UI线程中使用它之前将其冻结.

您必须自己加载它:

public static async Task<BitmapImage> GetNewImageAsync(Uri uri)
{
    BitmapImage bitmap = null;
    var httpClient = new HttpClient();

    using (var response = await httpClient.GetAsync(uri))
    {
        if (response.IsSuccessStatusCode)
        {
            using (var stream = new MemoryStream())
            {
                await response.Content.CopyToAsync(stream);
                stream.Seek(0, SeekOrigin.Begin);

                bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.StreamSource = stream;
                bitmap.EndInit();
                bitmap.Freeze();
            }
        }
    }

    return bitmap;
}
Run Code Online (Sandbox Code Playgroud)

或更短的BitmapFrame.Create,返回已经冻结的BitmapSource:

public static async Task<BitmapSource> GetNewImageAsync(Uri uri)
{
    BitmapSource bitmap = null;
    var httpClient = new HttpClient();

    using (var response = await httpClient.GetAsync(uri))
    {
        if (response.IsSuccessStatusCode)
        {
            using (var stream = new MemoryStream())
            {
                await response.Content.CopyToAsync(stream);
                stream.Seek(0, SeekOrigin.Begin);

                bitmap = BitmapFrame.Create(
                    stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            }
        }
    }

    return bitmap;
}
Run Code Online (Sandbox Code Playgroud)

请注意,第二种方法需要将Image属性的类型更改为BitmapSource(甚至更好的是ImageSource),这无论如何都会提供更大的灵活性.


没有任何手动下载的替代方法可能如下所示.它也不需要冻结BitmatImage,因为它不是在Task线程中创建的.

public static Task<BitmapSource> GetNewImageAsync(Uri uri)
{
    var tcs = new TaskCompletionSource<BitmapSource>();
    var bitmap = new BitmapImage(uri);

    if (bitmap.IsDownloading)
    {
        bitmap.DownloadCompleted += (s, e) => tcs.SetResult(bitmap);
        bitmap.DownloadFailed += (s, e) => tcs.SetException(e.ErrorException);
    }
    else
    {
        tcs.SetResult(bitmap);
    }

    return tcs.Task;
}
Run Code Online (Sandbox Code Playgroud)