1

I have the same problem as stated in this question, and the question is answered and the answer seems also to (theoretically) work in my problem. But I can't figure out how to implement the answer provided.

It suggest that when loading multiple images I batch them and just do a few and then use the dispatcher to start working on the next few.

I tried to write a function called LoadNextFive(int startIndex) and in the end of the function it just called itself like this: this.Dispatcher.BeginInvoke(() => { LoadNextFive(startIndex + 5); }); but it just didn't seem to work. Am I using the dispatcher wrong or am I implementing the answer wrong?

--EDIT-- I currently tried to just load 1 image at the time.

public void LoadNextImage()
{
    if(m_enumerator.MoveNext())
    {
        if (!m_bitmapSources.ContainsKey(m_enumerator.Current))
        {
            ZipEntry imageEntry = m_zip.GetEntry(m_enumerator.Current);
            using (Stream imageStream = m_zip.GetInputStream(imageEntry))
            {
                BitmapImage source = new BitmapImage();
                source.SetSource(imageStream);

                m_bitmapSources.Add(m_enumerator.Current, source);
            }

            m_dispatcher.BeginInvoke(() => LoadingTemplate.ChangeText(this, "")); //change loadingtext (provides % in future) and it calls this function again
        }
        else
        {
            m_dispatcher.BeginInvoke(() => LoadNextImage());
        }
    }else{
        //starts after every image is done loading
        LoadPages(); 
        LoadMonths();

        OnLoadComplete(new EventArgs());
    }
}
Community
  • 1
  • 1
SynerCoder
  • 12,493
  • 4
  • 47
  • 78

2 Answers2

1

It seemed that when I rewrote my code I forgot a part to rewrite. Hence still the bug. The code above works fine. So my question is now obsolete.

SynerCoder
  • 12,493
  • 4
  • 47
  • 78
0

The question and answer you refer to is regarding how many images you can load at once into an application domain and the resulting memory pressure. Your question seems about doing loading of images asynchronously with the Dispatcher.

For batching, I would use the Task Parallels Library (TPL). It has a ContinueWith method that would work well for doing some work and the continuing when the initial work is done.

TPL provides some really nice feature around calling several chained tasks asynchronously, and then calling back on the UI thread (as I assume you want to display the images somewhere in the UI).

Geoff Cox
  • 6,102
  • 2
  • 27
  • 30
  • I am also loading lots of images at the same time. The accepted answer comes from microsofts bug response and they suggested I use the dispatcher. I dont want to load them asyn but they said that the process needs to return to the UI so the reference to the bitmap can be cleaned up. – SynerCoder Nov 11 '11 at 18:54