christiangobo
christiangobo

Reputation: 530

DispatcherTimer and WebClient.DownloadStringAsync throw "WebClient does not support concurrent I/O operations" exception

I need help with this code

WebClient client = new WebClient();
    string url = "http://someUrl.com"

    DispatcherTimer timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromSeconds(Convert.ToDouble(18.0));
                timer.Start();

                timer.Tick += new EventHandler(delegate(object p, EventArgs a)
                {
                     client.DownloadStringAsync(new Uri(url));

                     //throw:
                     //WebClient does not support concurrent I/O operations.
                });

                client.DownloadStringCompleted += (s, ea) =>
                {
                     //Do something
                };

Upvotes: 0

Views: 1152

Answers (1)

Drew Marsh
Drew Marsh

Reputation: 33379

You're using a shared WebClient instance and the timer is obviously causing more than one download to occur at a time. Spin up a new client instance each time in the Tick handler or disable the timer so it won't tick again while you're still handling the current download.

timer.Tick += new EventHandler(delegate(object p, EventArgs a)
{
    // Disable the timer so there won't be another tick causing an overlapped request
    timer.IsEnabled = false;

    client.DownloadStringAsync(new Uri(url));                     
});

client.DownloadStringCompleted += (s, ea) =>
{
    // Re-enable the timer
    timer.IsEnabled = true;

    //Do something                
};

Upvotes: 1

Related Questions