DispatcherTimer和WebClient.DownloadStringAsync抛出“WebClient不支持并发I / O操作”异常

时间:2011-05-26 18:17:12

标签: c# multithreading concurrency dispatchertimer

我需要有关此代码的帮助

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
                };

1 个答案:

答案 0 :(得分:1)

您正在使用共享的WebClient实例,并且计时器显然会导致一次发生多个下载。每次在Tick处理程序中启动一个新的客户端实例或禁用计时器,以便在您仍在处理当前下载时不会再次打勾。

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                
};