title: Download multiple files in parallel using c#
body: <p>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.</p>
  
  <pre><code>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
  {
      /// &lt;summary&gt;
      /// Interaction logic for MainWindow.xaml
      /// &lt;/summary&gt;
      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 "&lt;a href=\".*\"&gt;(?&lt;name&gt;.*)&lt;/a&gt;";
              }
              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(() =&gt; {
                         listbox.Items.Add(url);
                     });
                 }
             }
          }
  
          private void Button_Click(object sender, RoutedEventArgs e)
          {
              DownloadP(listofFiles);
          }
      }
  }
  </code></pre>