Creating heavy user controls in WPF
I know that I cannot spawn different threads and put it in the UI thread
to add it in the Visual Tree as it will throw an exception that it cannot
access that object because a different thread owns it.
My current scenario is that I am heavily creating UI controls runtime, say
like 200 (FrameworkContentElement) controls and add it to the DockWindow.
Is it possible for me not to freeze the UI while creating this and try to
load them to the UI thread? I cannot even show a progress dialog because
that will use the UI thread while showing the dialog while doing work on
another thread, that is okay if what I need to handle is data and put it
in the UI but this time I need to create these UI controls.
One approach I've thought is create the UI controls and serialize them
into MemoryStream and load them to the UI thread, one problem in here is
that I have to re-attach the DataContext to the controls but that is fine,
at that moment I can delegate it to another thread. Problem still is that
is this feasible to do?
I tried mixing Task and Thread object to make the ApartmentState to 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;
}
No comments:
Post a Comment