I know that I cannot spawn different threads and put it in a UI thread to add it to the visual tree, because it will throw an exception that cannot access this object because it has a different thread.
My current scenario is that I strongly create a user interface control environment, for example, like 200 (FrameworkContentElement) controls and add it to DockWindow. Is it possible for me not to freeze the user interface while creating this and try to load them into the user interface thread? I canโt even show the progress dialog, because it will use the user interface thread when showing the dialog when working on another thread, itโs fine if I need to process the data and put it in the user interface, but this time I need to create these Controls user interface.
One approach that I thought was creating user interface controls and serializing them into a MemoryStream and loading them into the user interface stream, one of the problems is that I have to re-bind the DataContext to the controls, but this is normal, in this moment I can delegate it to another thread. The problem is still that it is doable ?
I tried mixing the Task object and Thread to make ApartmentState STA, but still no luck.
public static Task<T> StartSTATask<T>(Func<T> func) { var tcs = new TaskCompletionSource<T>(); Thread thread = new Thread(() => { try { tcs.SetResult(func()); } catch (Exception e) { tcs.SetException(e); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); return tcs.Task; }
EDIT . These controls are again FrameworkContentElement; virtualizing the controls in this scenario will not help. This is with FlowDocument controls creating runtime controls. Say Runs, Tables, Paragraphs, etc. . Therefore ListBox, TreeViews , etc. Not applicable in this scenario.
source share