在C#中下载fileasync之后无法执行下一个代码



我在youtube下载器时正在使用WebClient.DownloadFileAsync,并且使用它有问题。

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。

您应该开始阅读异步编程的最佳实践,并注意其中一个宗旨是" async一直"。

应用于您的代码,无论您的代码所在的代码/类别本身都应该是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");
}

最新更新