在 Silverlight 中访问单个 ObservableCollection 的多个异步方法
在 Silverlight 应用程序中,我需要下载大量文件。当文件下载完成后,我需要更新 ObservableCollection 对象。这是我正在使用的代码:
private void downloadFiles(List<string> files)
{
foreach (var file in files)
{
string _file = file;
new WebClient().OpenReadTaskAsync(new Uri(_file)).ContinueWith(t1 =>
{
Stream stream = t1.Result;
byte[] buffer = new byte[stream.Length];
stream.ReadAsync(buffer, 0, (int)stream.Length).ContinueWith(t2 =>
{
myObservableCollection.Add(_file); //An Exception is thrown.
});
});
}
}
当尝试添加到 myObservableCollection 时抛出异常:
无法在 CollectionChanged 或 PropertyChanged 事件期间更改 ObservableCollection。
解决此问题的一种方法是等待每个 OpenReadTaskAsync,但这样我就不会最大化 I/O。我还遇到了 ReaderWriterLock ,它看起来可以提供帮助,但不幸的是它在 Silverlight 中不可用。
我该如何处理这个问题?
In a Silverlight app I need to download a large amount of files. When a file finished downloading I need to update an ObservableCollection object. This is the code I am using :
private void downloadFiles(List<string> files)
{
foreach (var file in files)
{
string _file = file;
new WebClient().OpenReadTaskAsync(new Uri(_file)).ContinueWith(t1 =>
{
Stream stream = t1.Result;
byte[] buffer = new byte[stream.Length];
stream.ReadAsync(buffer, 0, (int)stream.Length).ContinueWith(t2 =>
{
myObservableCollection.Add(_file); //An Exception is thrown.
});
});
}
}
When trying to add to myObservableCollection An exception is thrown:
Cannot change ObservableCollection during a CollectionChanged or PropertyChanged event.
One way to fix that is to await on each OpenReadTaskAsync, but then I won't be maximizing the I/O. I also came across a ReaderWriterLock which look like it can help, but unfortunately it's not avaible in Silverlight.
How can I handle this issue ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用以下命令在 UI 线程上序列化更新
ObservableCollection
:You could serialize updating the
ObservableCollection
on the UI thread using this: