-3

When I attempt to call DownloadFileAsync my program crashes with the error "WebClient does not support concurrent I/O operations." What should I do to fix this?

        WebClient klient = new WebClient();

        MatchCollection matches = Regex.Matches(storage, pattern);

        Match[] odkazy = new Match[matches.Count];
        List<string> neco = new List<string> { };

        for (int i=0;i<matches.Count;i++)
        {
            matches.CopyTo(odkazy, 0);
            string ano = odkazy[i].ToString();
            neco.Add(ano);
            klient.DownloadFileAsync(new Uri(neco[i]), @"c:\picture{0}.png",i);
            Debug.WriteLine(neco[i]);
        }
Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
Tomas Gryzbon
  • 97
  • 3
  • 13
  • Is there an error message...? Are you trying to make us debug your code blind? :P – eddie_cat Sep 25 '14 at 21:32
  • In IntelliTrace it says: Exception:Thrown: "WebClient does not support concurrent I/O operations." (System.NotSupportedException) A System.NotSupportedException was thrown: "WebClient does not support concurrent I/O operations." – Tomas Gryzbon Sep 25 '14 at 21:34

1 Answers1

0

You need to use a new WebClient instance for each download; it can only do one at a time and you're trying to do a bunch rapidly with your for loop. Initialize a new one in each iteration:

for (int i=0;i<matches.Count;i++)
{
    matches.CopyTo(odkazy, 0);
    string ano = odkazy[i].ToString();
    neco.Add(ano);
    WebClient klient = new WebClient();
    klient.DownloadFileAsync(new Uri(neco[i]), @"c:\picture{0}.png",i);
    Debug.WriteLine(neco[i]);
}

Alternatively you can "chain" the downloads and start the next one in the DownloadFileCompleted event of the single web client.

eddie_cat
  • 2,527
  • 4
  • 25
  • 43