2

I am trying to find a way to add multiple (100+ with high amount of data) controls to a WPF GUI without blocking the GUI thread by itself. That's how i create the controls currently:

I create the controls asynchronous in a parallel thread and i am able to add them to the GUI but when it comes to container.Children.Add() the GUI is blocked.

My first try was creating them by a task in a async method..

var a = Task.Factory.StartNew(() =>
{
    foreach (UserElement element in userElements)
        this.Dispatcher.Invoke(() => { UserElementsContainer.Children.Add(element); });
});
await a; //Won't work with or without await.

Is there another way?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Marc
  • 103
  • 17
  • 2
    It is not a good idea to do this in the first place because all GUI related stuff should be handled by the GUI thread. Even if you succeed you are bound to get into trouble. – Philip Stuyck Aug 24 '15 at 09:16
  • Can you add some more code? You call the Dispatcher on THIS. but is that also the UserElementsContainer? If not it can block – Blaatz0r Aug 24 '15 at 09:17
  • THIS is the current WPF control (UserManagement) which is embedded in the WPF window. UserElementsContainer is part of the UserManagement. – Marc Aug 24 '15 at 09:18
  • _"add multiple (100+ with high amount of data) controls"_ - that amount of marshalling via `this.Dispatcher.Invoke()` is going to place considerable strain on the UI message pump –  Aug 24 '15 at 09:27

1 Answers1

4

You should rather use virtualisation and load controls as you need to display them - this way you reduce the amount of time required to load the controls as you are only showing a few at a time.

Check out this example which demonstrates a virtualised Canvas control. Microsoft Virtualized WPF Canvas

And also this other post for more virtualization technology references: Resources and guides to UI virtualization in WPF

Community
  • 1
  • 1
toadflakz
  • 7,764
  • 1
  • 27
  • 40