views:

146

answers:

3

In C#, Suppose I am in a form, and I pressed a button I made to close it.

this.Close();
some_action(); //can I do this??

can I perform another action after I closed the form or does the thread die and everything after that is lost?

+2  A: 

If you try to manipulate the form or any of it's controls after calling Close you're going to run into trouble. However there's nothing preventing you from calling some other method - for instance a logging method - after calling Close.

Paul Alexander
+2  A: 

Depends on what you are trying to do and the context of the statement. If the form being closed is the main form which owns the message loop, you can't do any UI related stuff (e.g. you can't display another MessageBox). If you are not doing it from another window (which doesn't own the message loop), you could do anything (even UI related) as long as you aren't manipulating the closed form object (you'll get ObjectDisposedException just like any disposed object).

By the way, the thread doesn't die as a result of Close. Closing the main window causes the message loop to terminate and not the thread itself. For example, the following program

static void Main() {
    Application.Run(new Form1());
    Application.Run(new Form2());
}

will display Form2 after Form1 is closed (using a newly created message loop). This proves that the thread is not dead.

Mehrdad Afshari
A: 

Handle FormClosing Event and do additional action in event handler.

Andrija