Calling a UI Class From a Non-UI Class.

B

bytebugs

Hi,

As a matter of principle I have refranied from creating an instance of
Form or UserControl from within a class that does not inherit from
System.Windows.Form.

I am looking for comments on Pros and Cons of the approach.

My logic has been that UI is always executed on the main application
thread. I use Control.InvokeRequired or delegates to ensure that I am
always changing something on the UI in the context of the main
thread.

If I were to create an instance of form in a non-ui class (one that
does not inherit from System.Windows.Form) I am inviting potential
trouble where someone may instantiate the non-ui class on a worker
thread which in turn will instantiate a form. Now we are in a
situation that we have a form that is created on worker thread.

Please put u'r comments on this subject. Is it a hard and fast rule
that create an instance of a UI/Form object only on the main thread?
 
G

Guest

Technically Forms have no tie whatsoever to the 'main' thread. The rule is,
you should mess with a window handle on another thread to the one that
created it. Most windows forms have a main form which was created on the
entry thread, therefore they are tied to ui processing on that thread. I have
an application launcher class in a UIFramework dll which has no base class
but controls the display of a splash screen for all my apps when they load.
It creates the splash screen in a secondary thread and thats fine as I
marshal all calls to the form onto that same secondary thread while my main
thread goes about loading the main form.
So the hard and fast rule is not to use a window handle (thats for forms and
controls) on a thread that didnt create it. if you might be on a thread that
didnt create the handle, ensure you always check Control.InvokeRequired and
use the Control.Invoke function to marshal calls onto the correct thread when
InvokeRequired is true.

HTH
 

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