WebClient does not support concurrent I/O operations

前端 未结 4 2131
温柔的废话
温柔的废话 2020-11-30 09:45

How can I get this error from with in the DownloadStringCompleted Event? Doesn\'t that mean, it\'s finished? Is there another event I can fire this from?

I get this

相关标签:
4条回答
  • 2020-11-30 10:15

    Instead of using WebClient use HttpClient to do parallel HTTP calls. Below code shows how to download files.

            HttpClient httpClient = new HttpClient();
            var documentList=_documentManager.GetAllDocuments();
            documentList.AsParallel().ForAll(doc =>
            {
    
                var responseResult= httpClient.GetAsync(doc.FileURLPath);
                using (var memStream = responseResult.Result.Content.ReadAsStreamAsync().Result)
                {
                    using (var fileStream =File.Create($"{filePath}\\{doc.FileName}"))
                    {
                        memStream.CopyTo(fileStream);
                    }
    
                }
            });
    
    0 讨论(0)
  • 2020-11-30 10:15

    The solution, I found is to use multiple WebClient objects, so to modify your pseudocode example; try

    var client = new WebClient("URL 1");
    client.CompletedEvent += CompletedEvent;
    client.downloadasync();
    
    void CompletedEvent(){
    Dosomestuff;
    var client2 = new WebClient();
    client2.downloadasync(); 
    }
    
    0 讨论(0)
  • 2020-11-30 10:23

    The WebClient only supports a single operations, it cannot download multiple files. You haven't shown your code, but my guess is that you are somehow firing a new request before the old is completed. My bet is that WebClient.IsBusy is true when you attempt to perform another fetch.

    See the following thread:

    wb.DownloadFileAsync throw "WebClient does not support concurrent I/O operations." exception

    0 讨论(0)
  • 2020-11-30 10:35

    The only answer is to create a new webclient within the scope of the Completed Event. You can't set it to new since webclient is readonly. Creating a new client is the only solution. This allows the old client to complete in the background. This does have slight memory implications since you are creating a new instance instead of reusing an old. But the garbage collector should keep it clean if your scope is setup right.

    0 讨论(0)
提交回复
热议问题