how create an instance of a windows form from a thread

hi i have the following problem
i have a Form1 (main form ) which have this code on a button

Asyn newSession = new Asyn(txtUserName.Text,txtPassword.Text.Trim(),this);
               Thread sessionThread=new Thread(new ThreadStart(newSession.StartSession));
               sessionThread.Start();

public class AsynSock : ISocketEventListener
     {

public Asyn(string user,string pass,Form1 l_form)
          {
               logForm=l_form;
               userName=user;
               password=pass;
          }
public void StartSession()
          {
if(Auth)
{
logForm.statues.Text="Done.";
                         MessageBox.Show("Welcome");
                         logForm.Hide();
                         Form2 frm=new frmMain();
                         frm.Show();
}
}
}

 the form shows but it hangs and gives not responding .
i couldn't figure where's the problem could anyone help me.
hema3iAsked:
Who is Participating?
 
jatinderalaghConnect With a Mentor Commented:
I think reason for this problem is u r not creating new form on STA UI thread

just try this

private void btnCreateForm_Click(object sender, System.EventArgs e)
            {
                  Thread sessionThread=new Thread(new ThreadStart(StartSession));
                  sessionThread.Start();

            }

            delegate void CallCreateForm();
            private void StartSession()
            {
                            // this is refrence to form1
                  this.Invoke(  new CallCreateForm(this.CreateMainForm));
            }

            private void CreateMainForm()
            {
                  Form2 frm = new Form2 ();
                  frm.Show();
            }

Hope this will help
regards
Jatinder
0
All Courses

From novice to tech pro — start learning today.