Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

Computer freeze when looping a large list of images in c# - Wpf

So i Have a very Simple software to call a multi Image list
and show them in a (Next) + (Previous) format like this :

enter image description here

and its work great for me but when i Hold on (NEXT) button to pass all items fast , after 10 or 20 item the whole window freezes and Lag , some recherche says to use background worker to prevent this so i tried to insert this :

var getImage = Directory.EnumerateFiles(DirName, Ext,
SearchOption.TopDirectoryOnly);

inside this :

Dispatcher.Invoke(DispatcherPriority.Background,
   new Action(() => /*### the Images output Here ###*/ ));

but the same Issues still happening

how to make it work correctly ?
and if there is any other way to do it i'll be happy to know it .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Dispatcher.Invoke schedules a delegate to be executed on the UI thread. You don't want to execute any potentially long-running code on the UI thread as this is what freezes your application.

If you want to call the Directory.EnumerateFiles on a background thread you could start a task:

Task.Factory.StartNew(()=> 
{
    //get the files on a background thread...
    return Directory.EnumerateFiles(DirName, Ext, SearchOption.TopDirectoryOnly);
}).ContinueWith(task => 
{
    //this code runs back on the UI thread
    IEnumerable<string> theFiles = task.Result; //...
}, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

Note that you cannot access any UI control on a background thread though so you should perform only the long-running work on the background thread and then you could use the ContinueWith method if you want to something with the results back on the UI thread, like for example setting the ItemsSource property of an ItemsControl or setting the Visibility property of a ProgressBar back to Collapsed or something.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...