I
I
Ilfar2017-05-24 20:42:08
C++ / C#
Ilfar, 2017-05-24 20:42:08

How to close Form2 via Form1 from another C# thread?

Through Form1 I launch Form2 with ProgressBar:

private void Button1_Click(object sender, EventArgs e)
        {
          if (backgroundWorker1.IsBusy != true)
            {
                frm2 = new Form2();
                frm2.Canceled += new EventHandler<EventArgs>(buttonCancel_Click);
                frm2.Show();
                backgroundWorker1.RunWorkerAsync();
            }
        }

If ts.Connect() returns false, then close Form2:
//делает трудоемкую работу

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            worker = sender as BackgroundWorker;
            //проверяем не запрошено-ли отмена фоновой операции
            if (worker.CancellationPending == true)
            {
                e.Cancel = true;
            }
            else
            {
                // Выполняем трудоемкую операцию 

                Tcp_Socket ts = new Tcp_Socket();
                bool ab=ts.Connect();
                if (ab == false)
                {
                    e.Cancel = true;
                      // Отмена асинхронной операции.
                backgroundWorker1.CancelAsync();

                // Закрываем Form2
               frm2.Close();
                    
                }

             
            }

        }

Throws an error on frm2.Close()
Illegal multi-thread operation: Attempt to access control 'Form2' from a thread other than the thread it was created on."
Please help! How to close Form2 from Form1 from another thread. Maybe with delegates somehow possible?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tex0, 2017-05-24
@tex0

Read here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question