views:

94

answers:

1

I have a set of Image elements that I use to download pictures. All the pictures have to be downloaded, but I wish to download the picture the user is looking at in the first place. If the user changes the viewed picture, I wish to cancel the downloads in progress to get the viewed picture as fast as possible.

To start a download I write: myImage.Source = new BitmapImage(theUri);.

How should I cancel it?

  • myImage.Source = null; ?
  • act on the BitmapImage ?
  • a better solution ?

I don't wish to download the picture by code to keep the benefit of the browser cache.

A: 

This is definitely doable -- I just tested it to make sure. Here is a quick class you can try:

public partial class Page : UserControl
{
    private WebClient m_oWC;
    public Page()
    {
        InitializeComponent();
        m_oWC = new WebClient();
        m_oWC.OpenReadCompleted += new OpenReadCompletedEventHandler(m_oWC_OpenReadCompleted);
    }

    void StartDownload(string sImageURL)
    {
        if (m_oWC.IsBusy)
        {
            m_oWC.CancelAsync();
        }
        m_oWC.OpenReadAsync(new Uri(sImageURL));
    }

    void m_oWC_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        BitmapImage oBMI = new BitmapImage();
        oBMI.SetSource(e.Result);
        imgMain.Source = oBMI;
    }
}

This works just like you wanted (I tested it). Everytime you call StartDownload with the URL of an image (presumably whenever a user clicks to the next image) if there is a current download in progress it is canceled. The broswer cache is also definitely being used (I verified with fiddler), so cached images are loaded ~ instantly.

David Hay
I wasn't aware of the WebClient class being actually an access to the browser download functionality. I trust you and validate the answer right now, even if I need some time to adapt it to our project. Thanks.
Mart