在Silverlight中访问单个ObservableCollection的多个异步方法

时间:2011-12-10 11:58:31

标签: silverlight-4.0 asynchronous thread-safety webclient 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中无法实现。

我该如何处理这个问题?

1 个答案:

答案 0 :(得分:0)

您可以使用以下命令序列化更新UI线程上的ObservableCollection

string _file = file;
var ui = TaskScheduler.FromCurrentSynchronizationContext();

...

.ContinueWith(t2 =>
    {
        myObservableCollection.Add(_file); //An Exception is thrown.                       
    }
    ,  ui );