user3171943
user3171943

Reputation: 1

Showing A Form In Thread - C#

Look at this code :

static Thread t1;
static ThreadStart ts1;

void my()
{
    this.Hide();
    Form2 frm2 = new From2();
    frm2.Show();
}

private void button1_Click(object sender, EventArgs e)
{
    ts1 = new ThreadStart(my);
    t1 = new Thread(ts1);
    t1.Start();
}

In my function there are some codes witch hides this form and opens form2 but there is a problem. When t1 runs and form2 is opened , the t1 is done so form2 will be closed too !

What should I do to fix this ?

Thanks

Upvotes: 0

Views: 57

Answers (2)

AmirHossein Rezaei
AmirHossein Rezaei

Reputation: 1420

change your method :

void my()
        {
            this.Invoke((MethodInvoker)delegate
            {
                this.Hide();
                Form frm2 = new Form();
                frm2.Show();
            });
        }

Upvotes: 0

usr
usr

Reputation: 171246

Do all UI calls on the UI thread. Always. Hide and open forms on the UI thread.

Upvotes: 2

Related Questions