多次调用 DownloadFileAsync

Call DownloadFileAsync multiple times

我正在制作 WPF 应用程序。我使用 WebClient 的 DownloadFileAsync 下载文件。我一次从文件夹中下载每个文件。我第一次调用 DownloadProtocol 它工作正常,但是当我想下载一个包含新文件的新文件夹时,我再次调用 DownloadProtocol 我的应用程序冻结了。我想同时下载更多。

            foreach (var x in res)

            {
                Console.WriteLine("111");
                await DownloadProtocol("http://cdn.something.com/rental/" + torrentId + "/" + x, savePath + torrentId + "/" + x);

            }

  public async Task DownloadProtocol(string address, string location)
    {

        Uri Uri = new Uri(address);
        using (WebClient client = new WebClient())
        {
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
            await client.DownloadFileTaskAsync(Uri, location);
        }
        /*while (client.IsBusy)
        {
            DoEvents();
        }*/
    }

    public void DoEvents()
    {
        DispatcherFrame frame = new DispatcherFrame();
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
            new DispatcherOperationCallback(ExitFrame), frame);
        Dispatcher.PushFrame(frame);
    }
    public object ExitFrame(object f)
    {
        ((DispatcherFrame)f).Continue = false;

        return null;
    }

    private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
    {
        // Displays the operation identifier, and the transfer progress.
        Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
            (string)e.UserState,
            e.BytesReceived,
            e.TotalBytesToReceive,
            e.ProgressPercentage);
    }

    private void Completed(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Cancelled == true)
        {
            Console.WriteLine("Download has been canceled.");
        }
        else
        {

            Console.WriteLine("Download completed!");
        }
    }

i want to download one file at a time

在不阻止您的 UI 的情况下,对吗?async/await 非常适合。你可以写一个方法 DownloadFile

public async Task DownloadFile(string url, string fileName)
{
    using (WebClient client = new WebClient())
    {
        client.DownloadProgressChanged += (o, e) =>
        {
            //Console.WriteLine(e.BytesReceived);
        };
        await client.DownloadFileTaskAsync(url, filename);
    }
}   

并像这里一样使用它

async void SomeClickHandler()
{
    var urls = new string[] {
        "http://google.com","http://whosebug.com"
    };

    foreach(var url in urls)
    {
        await DownloadFile(url, filename);
    }
}