Unable to execute next code after DownloadFileAsync in C#?

187 Views Asked by At

I'm using WebClient.DownloadFileAsync while making youtube downloader and I have problem using it.

WebClient client = new WebClient();
Process.Text("", "Downloading video data...", "new");
client.DownloadFileAsync(new Uri(this.VidLink), this.path + "\\tempVid"); // Line3
Process.Text("", "Downloading audio data...", "old");
client.DownloadFileAsync(new Uri(this.AudLink), this.path + "\\tempAud"); // Line5

FFMpegConverter merge = new FFMpegConverter();
merge.Invoke(String.Format("-i \"{0}\\tempVid\" -i \"{1}\\tempAud\" -c copy \"{2}{3}\"", this.path, this.path, dir, filename)); // Line8
merge.Stop();
Process.Text("", "Video merging complete", "new");

Process is another class I'm using, and it works quite well, so never mind about it. But where I am having problem is after executing Line 3. Line 3 and 4 are executed very well, and Line 5 won't be executed. When I used DownloadFile instead of DownloadFileAsync, the code worked very well, so this.AudLink is no problem. Line 5 also works very well when I delete Line 3.

Similarly, When I delete Line 3 and Line 5 goes very well, Line 8 won't be executed. So what's the problem with this code? Should I kill the process used by client or something?

++) I'm not going to use youtube-dl during downloading video data, so please don't tell me to use youtube-dl instead.

1

There are 1 best solutions below

1
On BEST ANSWER

You should start off reading the best practices for async programming and note that one of the tenets is "async all the way".

Applied to your code, whatever method/class your code is inside of should itself be async. At that point, you can await your async downloads

private async Task DoMyDownloading()
{
  WebClient client = new WebClient();
  Process.Text("", "Downloading video data...", "new");
  await client.DownloadFileAsync(new Uri(this.VidLink), this.path + "\\tempVid"); // Line3
  Process.Text("", "Downloading audio data...", "old");
  await client.DownloadFileAsync(new Uri(this.AudLink), this.path + "\\tempAud"); // Line5

  FFMpegConverter merge = new FFMpegConverter();
  merge.Invoke(String.Format("-i \"{0}\\tempVid\" -i \"{1}\\tempAud\" -c copy \"{2}{3}\"", this.path, this.path, dir, filename)); // Line8
  merge.Stop();
  Process.Text("", "Video merging complete", "new");
}