Multiple WebClients not working?

后端 未结 1 663
鱼传尺愫
鱼传尺愫 2021-01-19 17:38

I am trying to download three files with three separate WebClients. I use this:

    void client1_OpenReadCompleted(object sender, OpenReadCompletedEventArgs          


        
相关标签:
1条回答
  • 2021-01-19 18:09

    I think what you're experiencing is a combination of two issues. The first one being that the number of concurrent WebRequest connections is limited to 2 by default. You can change that by creating a class derived from WebClient and overriding the GetWebRequest method like so:

    public class ExtendedWebClient : WebClient
    {
        /// <summary>
        /// Gets or sets the maximum number of concurrent connections (default is 2).
        /// </summary>
        public int ConnectionLimit { get; set; }
    
        /// <summary>
        /// Creates a new instance of ExtendedWebClient.
        /// </summary>
        public ExtendedWebClient()
        {
            this.ConnectionLimit = 2;
        }
    
        /// <summary>
        /// Creates the request for this client and sets connection defaults.
        /// </summary>
        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address) as HttpWebRequest;
    
            if (request != null)
            {
                request.ServicePoint.ConnectionLimit = this.ConnectionLimit;
            }
    
            return request;
        }
    }
    

    The second problem I see is that you're not closing/disposing of the Stream returned when you call OpenRead, so it would appear that the two requests do not complete until such time when the Garbage Collector decides to kick in and close those streams for you.

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