在C#中循环播放大量图像时计算机冻结-WPF [英] Computer freeze when looping a large list of images in c# - Wpf

查看:230
本文介绍了在C#中循环播放大量图像时计算机冻结-WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个非常简单的软件可以调用多图像列表
并以( Next )+( Previous )格式显示,如下所示:

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

及其工作对我来说很好,但是当我按住(NEXT)按钮上的快速通过所有项目时,在10或20个项目之后,整个窗口冻结和Lag ,一些recherche表示要使用后台工作程序来防止这种情况,所以我尝试插入此代码:

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 ###*/ ));

但仍然存在相同的问题

如何使其正常工作?
如果还有其他方法可以解决,我将很高兴知道.

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

推荐答案

Dispatcher.Invoke安排要在UI线程上执行的委托.您不想在UI线程上执行任何可能长时间运行的代码,因为这会冻结您的应用程序.

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.

如果要在后台线程上调用Directory.EnumerateFiles,则可以启动任务:

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

请注意,尽管您不能在后台线程上访问任何UI控件,所以您应该仅在后台线程上执行长时间运行的工作,然后如果需要返回结果,可以使用ContinueWith方法. UI线程,例如设置ItemsControl的ItemsSource属性或将ProgressBarVisibility属性设置回Collapsed之类.

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.

这篇关于在C#中循环播放大量图像时计算机冻结-WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆