I have a listOfFilesToDownload
. I want to download all files in list in parallel
.........
Parallel.ForEach(listOfFilesToDownload, (file) =>
{
SaveFile(file, myModel);
});
private static void SaveFile(string file, MyType myModel)
{
filePath = "...";
try
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileTaskAsync(file, filePath)
}
//some time consuming proccess with downloaded file
}
catch (Exception ex)
{
}
}
In SaveFile
method I download the file, then I want to wait till it is downloaded, then make some processing with this file, and wait till this processing is finished. The full iteration have to be - download file and process it
So, the questions are:
- how to wait till the file is downloaded in the best way, so nothing is blocked and with maximum performance (I mean if I would use just
DownloadFile
it will block the thread till the file downloading, and I think this is not so good) - How to ensure that the file is downloaded and only then start processing it (cause if I start to process not existing file or not fully downloaded file I will have an error or wrong data)
- How to be sure processing with file is finished (because I tried to use
webClient.DownloadFileCompleted
event and process the file there, but I didn't manage to ensure that the processing is finished, example down below)
In complex the question is how to wait for a file to download asynchronously AND wait till it's processed
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileCompleted += DownloadFileCompleted(filePath, myModel);
webClient.DownloadFileTaskAsync(file, filePath);
}
DownloadFileCompleted returns AsyncCompletedEventHandler:
public static AsyncCompletedEventHandler DownloadFileCompleted(string filePath, MyType myModel)
{
Action<object, AsyncCompletedEventArgs> action = (sender, e) =>
{
if (e.Error != null)
return;
//some time consuming proccess with downloaded file
};
return new AsyncCompletedEventHandler(action);
}
Many thanks in advance!