Reputation: 4305
I am loading a user control inside a panel on a button click. But the UI will freeze for 3 or 4 seconds.
var uc = new TargetUserControl();
panel.Controls.Add(uc);
I can create user control in another thread.
TargetUserControl uc = null;
await Task.Run(() => { uc = new TargetUserControl(); });
panel.Controls.Add(uc);
but the main part of freezing is panel.Controls.Add(uc);
.
Note that the user control does not contain any data loading etc., it's is just a bunch of UI objects, such as buttons, labels, grid with a theme design.
How to avoid it, or make the freezing time very very small?
Upvotes: -2
Views: 81
Reputation: 280
Try to suspend layout before adding controls: In the code below I added a loading spinner to give a life to the process.
var _loader = new LoadingSpinner(); // Simple loading animation
panel.Controls.Add(_loader);
var uc = await Task.Run(() =>
{
var control = new TargetUserControl();
control.CreateControl(); // Force handle creation in background
return control;
});
panel.SuspendLayout();
panel.Controls.Remove(_loader );
panel.Controls.Add(uc);
panel.ResumeLayout(false); // Use false if you don't need immediate layout
Upvotes: -1