0

WebClient.DownloadFileAsync在制作 youtube 下载器时正在使用它,但我在使用它时遇到了问题。

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是我正在使用的另一个类,它工作得很好,所以别介意。但是我遇到的问题是在执行第 3 行之后。第 3 行和第 4 行执行得很好,第 5 行不会执行。当我使用DownloadFile代替时DownloadFileAsync,代码运行良好,所以this.AudLink没问题。当我删除第 3 行时,第 5 行也运行良好。

同样,当我删除第 3 行并且第 5 行运行良好时,第 8 行将不会执行。那么这段代码有什么问题呢?我应该杀死使用的进程client还是什么?

++) 我不会youtube-dl在下载视频数据时使用,所以请不要告诉我使用 youtube-dl 代替。

4

1 回答 1

1

您应该开始阅读异步编程的最佳实践,并注意其中一个原则是“一路异步”。

应用于您的代码,您的代码所在的任何方法/类本身都应该是async. 那时,您可以进行await异步下载

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");
}
于 2017-09-27T10:07:36.373 回答