Task wrap a synchronisation process isn't awaited

1904 views c#
10

My application WPF MVVM loads the files (almost 10000 files) in a folder. ProgressExplorerValue is the value of a progress bar.

public async Task ChargeFolderAsync()
{
    IsTaskConversionFinish = false;
    var rs = await Task.Run(() => LoadEntriesInFolder());
    IsTaskConversionFinish = true;
    ProgressExplorerValue = 0;
}

public IEnumerable<Record> LoadEntriesInFolder()
 {
     var rs = new List<Record>();
     var di = new DirectoryInfo(InitPath).EnumerateFiles();
     double factorPercent = di.Count() == 0 ? 0 : 100d / di.Count();            

     foreach (var file in di)
     {
         Record rc = new Record()
         {
             MetaName = file.Name,
             MetaPath = file.FullName
         };
         rs.Add(rc);
         ProgressExplorerValue += factorPercent;
     }
     return rs;
 }

The task isn't awaited at the line await Task.Run(() => LoadEntriesInFolder());. When I debug, it jumps from this line to next line without a break even that the method LoadEntriesInFolder hasn't yet completed.

answered question

Add ToList() after EnumerateFiles(). This might be enumeration problem

Or use GetFiles instead of EnumerateFiles. In either case

1 Answer

0

When doing
await Task.Run(() => LoadEntriesInFolder());
your awaiting for the return value of the Run(); method and not until the Task is finished.
try
Task.Run(() => LoadEntriesInFolder()).Wait();

posted this

Have an answer?

JD

Please login first before posting an answer.