In a pursuit for more responsive way to update ListBox with large number of items I turned to Rx. This is my implementation of it:
ObservableCollection<FileData> _fileCollection = new ObservableCollection<FileData>();
public ObservableCollection<FileData> FileCollection { get { return _fileCollection; } }
public static object _fileCollectionLock = new object();
public Subject<FileData> subject = new Subject<FileData>();
public MainWindow( )
{
InitializeComponent();
BindingOperations.EnableCollectionSynchronization(_fileCollection, _fileCollectionLock);
UpdateFileList(subject);
}
private void UpdateFileList(IObservable<FileData> sequence)
{
sequence.Subscribe(value=>_fileCollection.Add(value));
}
private void ListFiles(string fullpath)
{
_fileCollection.Clear(); //crashed once
Task.Factory.StartNew(() =>
{
DirectoryInfo info = new DirectoryInfo(fullpath);
IEnumerable files = info.EnumerateFiles(Filter + "*", SearchOption.TopDirectoryOnly,true);
foreach (FileInfo file in files)
{
...
FileData fd = new FileData(filename, filedate, filesize, fileext);
subject.OnNext(fd);
It happened once that in my code crashed on _fileCollection.Clear(); (Forgot the error, sorry). Do I need to use locks and where?