0

pre information

I am following Microsoft learning Documentation to copy a large file and at the same time report progress on the operation.

This is my code:

Task copy = CopyFileAsync(fi, targetFile);
while (!copy.IsCompleted && !copy.IsFaulted)
{
    double prog = (double)((copiedBytes + targetFile.Length) / (double)totalBytes)*100;
    progress.Report(prog);
    Task.Delay(200).Wait();
}
private async Task CopyFileAsync(FileInfo source, FileInfo target)
{
    File.Copy(source.FullName, target.FullName, true);
}

to my understanding this is in line with the sample code from the documentation:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

Coffee cup = PourCoffee();
Console.WriteLine("Coffee is ready");

Task<Egg> eggsTask = FryEggsAsync(2);
Task<Bacon> baconTask = FryBaconAsync(3);
Task<Toast> toastTask = ToastBreadAsync(2);

Toast toast = await toastTask;
ApplyButter(toast);
ApplyJam(toast);
Console.WriteLine("Toast is ready");
Juice oj = PourOJ();
Console.WriteLine("Oj is ready");

Egg eggs = await eggsTask;
Console.WriteLine("Eggs are ready");
Bacon bacon = await baconTask;
Console.WriteLine("Bacon is ready");

Console.WriteLine("Breakfast is ready!");

Issue
The code runs synchronously. First the task is completed, and only afterwards is the update loop reached.

Update #1 The following code works but is not what is suggested in the documentation. Would this be the "correct" way to run the task asynchronously?

Task copy = Task.Run(() => {CopyFileAsync(fi, targetFile);});
while (!copy.IsCompleted && !copy.IsFaulted)
{
    double prog = (double)((copiedBytes + targetFile.Length) / (double)totalBytes)*100;
    progress.Report(prog);
    Task.Delay(200).Wait();
}
julian bechtold
  • 1,875
  • 2
  • 19
  • 49

0 Answers0