I'm trying to use a Microsoft.Windows.APICodePack.Shell.ShellContainer as ItemsSource for a ListBox, showing each child's (ShellObject) Thumbnail and Name via ListBox.ItemTemplate. The problem arises when ShellContainer refers to a VERY BIG folder (say more than one thousand files): if I simply declare
ShellContainer source=ShellObject.FromParsingName(@"C:\MyFolder") as ShellContainer:
listBox1.ItemsSource=source.GetEnumerator();
it freezes the UI for two or three minutes, then displays ShellContainer's content all at once. The best workaround I've found is to create an async filler class like this
class AsyncSourceFiller
{
private ObservableCollection<ShellObject> source;
private ShellContainer path;
private Control parent;
private ShellObject item;
public AsyncSourceFiller(ObservableCollection<ShellObject> source, ShellContainer path, Control parent)
{
this.source = source;
this.path = path;
this.parent = parent;
}
public void Fill()
{
foreach (ShellObject obj in path)
{
item = obj;
parent.Dispatcher.Invoke(new Action(Add));
Thread.Sleep(4);
}
}
private void Add()
{
source.Add(item);
}
}
and then call it via
ObservableCollection<ShellObject> source = new ObservableCollection<ShellObject>();
listBox1.ItemsSource = source;
ShellContainer path = ShellObject.FromParsingName(@"C:\MyFolder"):
AsyncSourceFiller filler = new AsyncSourceFiller(source, path, this);
Thread th = new Thread(filler.Fill);
th.IsBackground = true;
th.Start();
This takes more time than the previous way, but doesn't freeze the UI and begins to show some content immediately. Is there any better way to obtain a similar behavior, possibly shortening total operation time?