I'm writing a simple console app that copies files from one place to another. I would like to do the copying asynchronously. It mostly seems to work, but some of the files being copied end up being zero length files or smaller than they should be, and cannot be opened.
Here is the relevant part of my code:
static async void CopyFiles()
{
foreach (string myFileName in filenameList) // get a list of files to copy.
{
Task xx = CopyDocumentAsync(myFileName);
xx.Wait(); // without this Wait some of the files are not copied properly.
}
}
static async Task CopyDocumentAsync(string myFileName)
{
if (!String.IsNullOrEmpty(myFileName))
{
using (FileStream source = File.Open(sourcePath +"\\" + myFileName, FileMode.Open))
{
using (FileStream destination = File.Create(destinationPath + "\\" + myFileName))
{
await source.CopyToAsync(destination);
}
}
}
}
I'm guessing that the problem is that the application is exiting before all the asynchronous copying has completed, but I'm not sure how to prevent that. I've added code to wait for each copy to complete copying before moving on, but that feels like it's defeating the point of doing the work asynchronously!
Is there a way to make this work so that all the file copies can be performed in parallel, and then either wait for every copy to be finished before closing the app, or allow the app to close without terminating the copy operation?