多次调用DownloadFileAsync

时间:2015-08-21 12:00:41

标签: c# wpf download webclient

我正在制作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!");
        }
    }

1 个答案:

答案 0 :(得分:2)

  

我想一次下载一个文件

如果没有阻止你的用户界面, 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://stackoverflow.com"
    };

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