图像不能在WPF中第二次加载时下载

时间:2011-02-13 05:25:39

标签: wpf http azure

我有一个名为MyBook的UserControl WPF应用程序,在Loaded上将触发后台线程以获取域对象列表,每个域对象都有一个到blob存储中托管的Azure映像的URL。

对于我回来的每个域对象,我添加了一个名为LazyImageControl的自定义控件的新实例,该控件将在后台从Azure下载图像并在完成后渲染图像。

这很好用,但是当我向场景中添加第二个MyBook控件时,由于某种原因图像不加载,我无法弄清楚为什么会这样。

以下是LazyImageControl

的代码
public LazyImageControl()
    {
        InitializeComponent();

        DataContextChanged += ContextHasChanged;
    }

    private void ContextHasChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        // Start a thread to download the bitmap...
        _uiThreadDispatcher = Dispatcher.CurrentDispatcher;
        new Thread(WorkerThread).Start(DataContext);
    }

    private void WorkerThread(object arg)
    {
        var imageUrlString = arg as string;
        string url = imageUrlString;

        var uriSource = new Uri(url);
        BitmapImage bi;
        if (uriSource.IsFile)
        {
            bi = new BitmapImage(uriSource);
            bi.Freeze();
            _uiThreadDispatcher.Invoke(DispatcherPriority.Send, new DispatcherOperationCallback(SetBitmap), bi);
        }
        else
        {
            bi = new BitmapImage();
            // Start downloading the bitmap...
            bi.BeginInit();
            bi.UriSource = uriSource;
            bi.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
            bi.DownloadCompleted += DownloadCompleted;
            bi.DownloadFailed += DownloadFailed;
            bi.EndInit();
        }

        // Spin waiting for the bitmap to finish loading...
        Dispatcher.Run();
    }

    private void DownloadFailed(object sender, ExceptionEventArgs e)
    {
        throw new NotImplementedException();
    }

    private void DownloadCompleted(object sender, EventArgs e)
    {
        // The bitmap has been downloaded. Freeze the BitmapImage
        // instance so we can hand it back to the UI thread.
        var bi = (BitmapImage)sender;
        bi.Freeze();

        // Hand the bitmap back to the UI thread.
        _uiThreadDispatcher.Invoke(DispatcherPriority.Send, new DispatcherOperationCallback(SetBitmap), bi);

        // Exit the loop we are spinning in...
        Dispatcher.CurrentDispatcher.InvokeShutdown();
    }

    private object SetBitmap(object arg)
    {
        LazyImage.Source = (BitmapImage)arg;
        return null;
    }

所以问题是,在第一次WorkerThread运行正常后执行此操作,但我从未收到DownloadCompletedDownloadFailed方法的回调,我不知道为什么......

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

不确定但是在设置应该触发图像加载的DownloadCompleted之前,您应该尝试附加DownloadFailedBitmapImage.UriSource事件处理程序,因此可能是它已加载在你的事件处理程序被附加之前(不是第一次因为加载需要一段时间但是然后图像被缓存并将立即加载)

另外:LazyImageControl继承了哪个类,所以如果不是,我可以测试它吗?