使用C#下载多个文件并行 [英] Download multiple files in parallel using c#

查看:291
本文介绍了使用C#下载多个文件并行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下载并行使用C#文件。对于这一点,我写了这个代码,这是工作完美,但问题是,用户界面是冻结

 使用系统; 
使用System.Collections.Generic;
:使用System.IO;
使用System.Linq的;使用System.Net
;
使用System.Text;使用System.Text.RegularExpressions
;
使用的System.Threading;使用System.Threading.Tasks
;使用System.Windows
;使用System.Windows.Controls的
;
使用System.Windows.Data;使用System.Windows.Documents
;
使用System.Windows.Input;使用System.Windows.Media
;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;使用System.Windows.Shapes
;
使用System.Windows.Threading程序;

命名空间FileDownloader
{
///<总结> $ B $为MainWindow.xaml
///< b ///交互逻辑; /总结>
公共部分类主窗口:窗口
{
私有静态诠释计数= 1;
私有静态串f =讲座;
私人字符串URL =www.someexample.com;

公共主窗口()
{
的InitializeComponent();
}

公共静态字符串GetDirectoryListingRegexForUrl(字符串URL)
{
如果(url.Equals(URL))
{
返回 &所述; A HREF = \* \。>(小于?名称> *)&下; / A>中;
}
抛出新NotSupportedException异常();
}

公共无效DownloadP(字符串[]的URL)
{
Parallel.ForEach(urls.ToList(),新ParallelOptions {MaxDegreeOfParallelism = 10},DownloadFile );
}用

私人无效DownloadFile(字符串URL)
{
(Web客户端的客户端=新的WebClient())
{
如果( url.EndsWith(PDF))
{
INT nextIndex = Interlocked.Increment(引用计数);

client.DownloadFile(URL,F + nextIndex +.PDF);
this.Dispatcher.Invoke(()=> {
listbox.Items.Add(URL);
});
}
}
}

私人无效Button_Click(对象发件人,RoutedEventArgs E)
{
DownloadP(listofFiles);
}
}
}


解决方案

您可以使用异步/的await 用新的 Web客户端方法 DownloadFileTaskAsync <结合/ code>。

 专用异步任务DownloadFile(字符串URL)
{
如果( !url.EndsWith(PDF))
{
的回报;
}使用

(VAR的客户=新的WebClient())
{
INT nextIndex = Interlocked.Increment(引用计数);

等待client.DownloadFileTaskAsync(URL,讲座+ nextIndex +.PDF);
listBox.Items.Add(URL);

}
}

私人异步无效Button_OnClick(对象发件人,RoutedEventArgs E)
{
button.IsEnabled = FALSE;
等待DownloadFiles(urlList);
button.IsEnabled = TRUE;
}

私人异步任务DownloadFiles(IEnumerable的<串> urlList)
{
的foreach(在urlList VAR URL)
{
等待DownloadFile(URL);
}
}


I want to download files in parallel using C#. For this, I have written this code which is working perfectly but the problem is that UI is freezing.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace FileDownloader
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static int count = 1;
        private static string f= "lecture";
        private string URL = "www.someexample.com";

        public MainWindow()
        {
            InitializeComponent();
        }

        public static string GetDirectoryListingRegexForUrl(string url)
        {
            if (url.Equals(URL))
            {
                return "<a href=\".*\">(?<name>.*)</a>";
            }
            throw new NotSupportedException();
        }

        public  void DownloadP(string[] urls)
        {
            Parallel.ForEach(urls.ToList(), new ParallelOptions { MaxDegreeOfParallelism = 10 }, DownloadFile);
        }

        private void DownloadFile(string url)
        {
           using(WebClient client=new WebClient())
           {
               if (url.EndsWith(".pdf"))
               {
                   int nextIndex = Interlocked.Increment(ref count);

                   client.DownloadFile(url, f + nextIndex + ".pdf");
                   this.Dispatcher.Invoke(() => {
                       listbox.Items.Add(url);
                   });
               }
           }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DownloadP(listofFiles);
        }
    }
}

解决方案

You can use async/await with conjunction with new WebClient method DownloadFileTaskAsync.

private async Task DownloadFile(string url)
{
    if (!url.EndsWith(".pdf"))
    {
        return;
    }

    using (var client = new WebClient())
    {
        int nextIndex = Interlocked.Increment(ref count);

        await client.DownloadFileTaskAsync(url, "lecture" + nextIndex + ".pdf");
        listBox.Items.Add(url);

    }
}

private async void Button_OnClick(object sender, RoutedEventArgs e)
{
    button.IsEnabled = false;
    await DownloadFiles(urlList);
    button.IsEnabled = true;
}

private async Task DownloadFiles(IEnumerable<string> urlList)
{
    foreach (var url in urlList)
    {
        await DownloadFile(url);
    }
}

这篇关于使用C#下载多个文件并行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆