Loading a Control on a Different Thread

P

Phil Jones

I'm trying to add a control to a form when a user clicks a button - the
contol takes a long time to load.

To make the app appear responsive, I want to do this in the background
(displaying a simple "Loading" message). How do I go about this? I've
tried creating a new thread, and useing the Control.BeginInvoke method - but
the result is that the control created within the different thread does not
appear (see example below).

Is this because the contol is created on a different thread. Please, what
is the correct way to program this type of behaviour.
Many thanks!

===
Phil Cockfield
(Auckland | Aotearoa)

==============================================

Imports System.Threading

Public Class UserControl1
Inherits UserControl
Delegate Sub dAddControl()

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim d As New dAddControl(AddressOf Me.AddControl)
Dim ar As IAsyncResult = d.BeginInvoke(Nothing, Nothing)
Me.BackColor = Color.Salmon
End Sub

Sub AddControl()
Dim c As New UserControl2
Me.Controls.Add(c)
c.Width = 350 : c.Height = 50
End Sub

End Class
 
J

Jon Skeet [C# MVP]

Phil Jones said:
I'm trying to add a control to a form when a user clicks a button - the
contol takes a long time to load.

To make the app appear responsive, I want to do this in the background
(displaying a simple "Loading" message). How do I go about this? I've
tried creating a new thread, and useing the Control.BeginInvoke method - but
the result is that the control created within the different thread does not
appear (see example below).

Is this because the contol is created on a different thread. Please, what
is the correct way to program this type of behaviour.

The control itself *must* be created on the UI thread. Do you know why
the control takes a long time to load? If you can separate the loading
part from the control instantiation part, you could put the load on a
separate thread, and just use the UI thread for the actual
instantiation.
 
P

Phil Jones

Ahh... now there's a plan! I can take all it's creation code out of the
constructor and put it in a "LoadStuff" method.

If the LoadStuff method creates further sub-controls, the problem will still
persist when passing execution to another thread won't it. This is why it's
taking time - it's loading a bunch of sub-controls and positioning then.
I'll try this out, and see if I get anywhere.

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top