简体   繁体   English

c#异步任务运行,返回函数带有参数

[英]c# Async task running with return value for a function with parameters

So I've searched the Net for ways of executing some heavy tasks async to keep the UI responsive. 因此,我在网上搜索了异步执行一些繁重任务以保持UI响应能力的方法。 And to be quite honest - I did not find anything that describes my actual situation in a way I can understand . 老实说-我没有找到能理解我实际情况的东西。

So I have this code snippet: 因此,我有以下代码片段:

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

What I actually want is to run the ReadIndexFile function with the paramether downloadPath to write the value of indexItems while allowing me to repaint and alter the UI and then wait for the Task to finish. 我真正想要的是使用ReadIndexFile downloadPath运行ReadIndexFile函数来写入indexItems的值,同时允许我重新绘制和更改UI,然后等待Task完成。

I've ran into so many problems with that piece of code that I just ask for an example for this particular scenario and a brief explanation. 我在这段代码中遇到了很多问题,我只是想为这种特定情况提供一个示例,并做一个简短的解释。

Any help would be greatly appreciated! 任何帮助将不胜感激!

EDIT Original snippet with plain old sync. 编辑带有简单旧同步的原始代码段。 execution to show what happens: 执行以显示发生了什么:

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;

Then there are some UI updates in another method which are not related to this data, just updating labels, buttons, etc. 然后,另一种方法中的一些UI更新与该数据无关,只是更新标签,按钮等。

The best way to do this is to add an asynchronous method async Task FileHandling.ReadIndexFileAsync(string path) . 最好的方法是添加一个异步方法async Task FileHandling.ReadIndexFileAsync(string path) If you can't make changes to FileHandling , try something like this: 如果您无法更改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.
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM