同时调用多个DownloadFileAsync阻止UI线程

时间:2015-08-22 20:53:38

标签: c# wpf multithreading task webclient

我正在创建一个WPF应用程序,我使用WebClient从Web服务器下载文件。我的代码现在一次下载一个文件并等待该文件完成,然后再开始下一个等等。 我有几个列表,其中存储文件的名称 - 如文件夹。当我点击第一个按钮时,下载开始下载第一个文件夹seqeuncy中的文件,但是当第一次下载正在进行中并且我想通过单击第二个按钮开始从第二个文件夹下载时,我的应用程序冻结。我希望我的应用程序同时运行多个DownloadFileAsync。 我试图为每次下载开始一个新的线程,但这似乎也不起作用。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

    }

    private void StartButton_Click(object sender, RoutedEventArgs e)
    {


        DownloadGameFile dlg = new DownloadGameFile();
        dlg.StartDownload(11825);

    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        DownloadGameFile dlg = new DownloadGameFile();
        dlg.StartDownload(11198);
    }
}
class DownloadGameFile
{
    private DownloadTorrentFile DLTorrent;

    //List of file that already exist
    private List<string> ExistFile = new List<string>();
    DirectoryInfo fileInfo;

    private string savePath = @"C:somewhere";
    public string path { get; set; }

    private bool isDelete = false;
    public DownloadGameFile()
    {
        DLTorrent = new DownloadTorrentFile();

    }
    public async void StartDownload(int torrentId)
    {
        try
        {
            DLTorrent.DecodeTorrent(torrentId);

            //Creates a folder to the game
            var newdic = Directory.CreateDirectory(savePath + torrentId);

            fileInfo = new DirectoryInfo(savePath + torrentId);
            //File info from a Directory
            FileInfo[] files = fileInfo.GetFiles();

            foreach (FileInfo i in files)
            {
                Console.WriteLine("Files exit " + i);
                if (DLTorrent.GameInfomation[i.Name] != i.Length)
                {
                    i.Delete();
                    isDelete = true;
                }
                else
                {
                    Console.WriteLine("add files ");
                    ExistFile.Add(i.Name);
                }

            }
            //Make a list which file not downloaded yet
            var res = DLTorrent.GameInfomation.Keys.Except(ExistFile);

            var nFiles = files.Length;
            if(nFiles == 0 || !isDelete)
            {
                nFiles++;
                foreach (var x in res)
                {
                    ((MainWindow)System.Windows.Application.Current.MainWindow).label1.Content = nFiles + " out of " + DLTorrent.GameInfomation.Keys.Count();
                    await DownloadProtocol("http://cdn.somewhere/rental/" + torrentId + "/" + x, savePath + torrentId + "/" + x);
                    nFiles++;
                }
            }
            else
            {
                foreach (var x in res)
                {

                    ((MainWindow)System.Windows.Application.Current.MainWindow).label1.Content = nFiles + " out of " + DLTorrent.GameInfomation.Keys.Count();
                    await DownloadProtocol("http://cdn.somewhere/rental/" + torrentId + "/" + x, savePath + torrentId + "/" + x);
                    nFiles++;
                }
            }
        }
        catch
        {

        }

    }


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

        Uri Uri = new Uri(address);
        using (WebClient client = new WebClient())
        {
            client.DownloadProgressChanged += (o, e) =>
            {
                Console.WriteLine(e.BytesReceived + " " + e.ProgressPercentage);
                ((MainWindow)System.Windows.Application.Current.MainWindow).DownloadBar.Value = e.ProgressPercentage;
            };

            client.DownloadFileCompleted += (o, e) =>
            {
                if (e.Cancelled == true)
                {
                    Console.WriteLine("Download has been canceled.");
                }
                else
                {

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

            };

            await client.DownloadFileTaskAsync(Uri, location);
        }

    }


}

1 个答案:

答案 0 :(得分:2)

你试过这个:

private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    DownloadGameFile dlg = new DownloadGameFile();
    await dlg.StartDownload(11825);
}

dlg.StartDownload必须返回任务。