简体   繁体   中英

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. 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.

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.

The best way to do this is to add an asynchronous method async Task FileHandling.ReadIndexFileAsync(string path) . If you can't make changes to FileHandling , try something like this:

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.
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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