How to use the dispatcher to load multiple images [closed]

六月ゝ 毕业季﹏ 提交于 2019-12-11 11:46:52

问题


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());
    }
}

回答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.




回答2:


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).



来源:https://stackoverflow.com/questions/8094355/how-to-use-the-dispatcher-to-load-multiple-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!