所以我在网上搜索了一些异步执行繁重任务以保持 UI 响应的方法。老实说——我没有找到任何能以我能理解的方式描述我的实际情况的东西。
所以我有这个代码片段:
List<myType> indexedItems = new List<myType>();
Task t = new Task.Run(() => indexedItems = FileHandling.ReadIndexFile(downloadPath));
lblProgress.Content = "Reading index file...";
lstItems.ItemsSource = null;
t.Wait();
我真正想要的是运行ReadIndexFile
带有参数的函数downloadPath
来写入值,indexItems
同时允许我重新绘制和更改 UI,然后等待任务完成。
我在这段代码中遇到了很多问题,我只是要求提供这个特定场景的示例和简要说明。
任何帮助将不胜感激!
使用普通的旧同步编辑原始片段。执行以显示发生了什么:
if (File.Exists(downloadPath + @"\index.sbmdi"))
{
lblProgress.Content = "Reading index file...";
lstMangas.ItemsSource = null;
indexedMangas = FileHandling.ReadIndexFile(downloadPath);
categoryList = Library.BuildCategoryList(indexedMangas);
lstMangas.ItemsSource = indexedMangas;
lblProgress.Content = "Ready.";
}
lblProgress.Content = "Ready.";
prgrssUpper.IsIndeterminate = false;
然后在另一种方法中有一些与此数据无关的 UI 更新,只是更新标签、按钮等。
最好的方法是添加一个异步方法async Task FileHandling.ReadIndexFileAsync(string path)
。如果您无法对 进行更改FileHandling
,请尝试以下操作:
async Task MySnippet(string downloadPath)
{
// Start reading the index file, but don't wait for the result.
Task<List<myType>> indexedItemsTask = Task.Run(() => FileHandling.ReadIndexFile(downloadPath));
// Alternatively, if you can add a method FileHandling.ReadIndexFileAsync:
// Task<List<myType>> indexedItemsTask = FileHandling.ReadIndexFileAsync(downloadPath);
// Update the UI.
lblProgress.Content = "Reading index file...";
lstItems.ItemsSource = null;
// *Now* wait for the result.
List<myType> indexedItems = await indexedItemsTask;
// Do stuff with indexedItems.
// ...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句