views:

146

answers:

1

hi,

I am using the below function to close the existing form and open a new form. I have a function running as thread which shud run in background always. when i call the below function from my function in thread, the thread is not doing its work after that. May be the thread is aborting. How to resolve this. Thanks.

static public void NewMainForm(Form main, bool ClosePreviousMain)
{ 
    if (main != null)
    {
    Global.ActiveForm = main.Text;
    if (ClosePreviousMain & MyContext.curMain != null)
    {
        MyContext.curMain.FormClosed -= new FormClosedEventHandler(main_FormClosed);
        if (Application.OpenForms.Count > 0)
        {
        MyContext.curMain.Invoke(new Action(MyContext.curMain.Dispose));
        }
    }
    MyContext.curMain = main;
    MyContext.curMain.FormClosed += new FormClosedEventHandler(main_FormClosed);
    MyContext.curMain.ShowDialog();
    }
}
+1  A: 

When you run an application the runtime creates a main (foreground) thread and start executing the entry point of your application i.e. Main method.

In GUI application when main method executes it launches a thread called the EDT (Event Dispatch Thread), another main (foreground) thread and your main thread exits after that (if it has nothing to do). However the application keeps running until a single main (foreground) thread is alive.

The method you are executing is a background thread (as you mentioned) when the GUI exits (after you close the form) all the main (foreground) thread are died hence your application dies with it. What you need to do is to run your background worker thread as a foreground thread so that all the thread created by a foreground thread is by default a foreground thread and thread created by a background thread is default to background thread.

So either join your main thread to wait for your background thread to get terminated (in this case you need to implement a way to stop your background thread). Or run your background thread as a foreground thread.

S M Kamran
By the way you can set the Thread.IsBackground property to [true or false] to make it a background thread.
S M Kamran
The thread is aborting. i checked in the taskmanager.
Anuya
Before starting your thread set the Thread.IsBackground = false; then check.
S M Kamran