繁体   English   中英

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

[英]DispatcherTimer and WebClient.DownloadStringAsync throw “WebClient does not support concurrent I/O operations” exception

我需要有关此代码的帮助

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

您正在使用共享的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                
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM