Reputation: 797
I am developing a plugin for an application, that application "consumes" my code (classLibrary), and executes the Init()
method inside his own Thread
.
Inside the Init() I have a while(true)
statement, so that my plugin can run continuously.
Yesterday, I started to make a windowsForm for configuration of my plugin (using XML), and now I want to show it, but it keeps vanishing. My code is as follows:
Doing this will show the form, but, it wont re-paint because it is launched on that same thread as the while(true) is.
MaForm settingsForm = null;
void init(){
While(true){
if(settingsForm == null){
settingsForm = new MaForm();
settingsForm.show();
}
}
}
Version that shows, but then vanishes.
MaForm settingsForm = null;
Thread worker = null;
void init(){
While(true){
if(worker == null){
worker = new Thread(new ThreadStart(formStuff));
worker.Start();
}
}
}
void formStuff()
{
if(settingsForm == null){
settingsForm = new MaForm();
settingsForm.show();
}
}
What am I doing wrong? Is there something about Threading I am missing? What do you guys think?
Upvotes: 3
Views: 165
Reputation: 75276
A good way of dealing with threading issues in C# is to comment out using System.Threading;
at the top of your classes and forms. You may have some compelling reason for showing forms with a Thread
, but probably not, since Form.Show()
is not a blocking call.
if you're trying to show a form from your Main()
method, try using ShowDialog()
instead. This call will block until the form is closed.
Upvotes: 0
Reputation: 47978
you can try this: create the form, enter the infinite loop, call DoEvents()
so that your form can process windows messages:
if(settingsForm == null){
settingsForm = new MaForm();
settingsForm.show();
}
while (settingsForm != null && settingsForm.Visible)
{
System.Windows.Forms.Application.DoEvents();
}
EDIT: may be you can replace the true
condition by a check on the SettingsForm
visibility. When the form is closed, it's a waste to stay in an infinite loop.
Upvotes: 0
Reputation: 564413
The thread is starting, showing your form, then finishing up and shutting down (which closes the form).
Showing a form on a separate thread is nearly always problematic. Forms require a message pump to be running - so they typically will only work properly if they're started and run on the GUI thread.
One option would be to invoke the function to show your form onto your main thread. This will make your form load (and run) on the main thread.
Alternatively, you can start an entire message pump on the form's thread, and set the thread to STA (this is important). However, I suggest avoiding this approach if possible.
Upvotes: 1