所以我有一个非常简单的软件来调用多图像列表
并以(Next
)+(Previous
)格式显示它们,如下所示:
它的工作对我来说很棒但是当我按住(下一个)按钮快速传递所有项目,10或20项后整个窗口冻结和滞后,一些recherche说使用后台工作人员来防止这种情况所以我试图插入这个:
var getImage = Directory.EnumerateFiles(DirName, Ext,
SearchOption.TopDirectoryOnly);
在里面:
Dispatcher.Invoke(DispatcherPriority.Background,
new Action(() => /*### the Images output Here ###*/ ));
但同样的问题仍在发生
如何让它正常工作? 如果还有其他办法,我会很高兴知道它。
Dispatcher.Invoke
计划在UI线程上执行委托。您不希望在UI线程上执行任何可能长时间运行的代码,因为这会冻结您的应用程序。
如果你想在后台线程上调用Directory.EnumerateFiles
,你可以开始一个任务:
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
属性或将Visibility
的ProgressBar
属性设置回Collapsed
或其他东西。