如何解决DispatcherTimer和WebClient.DownloadStringAsync引发“ WebClient不支持并发I / O操作”异常
| 我需要有关此代码的帮助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”实例,并且计时器显然导致一次进行多个下载。每次在
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
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。