0

While using forms in C# for a project, i have my main Form (mainForm). This form, when clicking the button1, it creates a new thread for the second Form (actionForm). This one, does the same as the main, when i click button1, it creates a new thread for the thid Form (registerForm). This third Form, when i close it, it must recreate the second form.

The problem is that, the threads keep running. The forms, were closed. But when i click the "X" in the third form, it loops, creating new actionsForms.

How can i stop the threads when creating new ones? Is there a better way to use the Forms?

Code:

namespace Lector
{
    public partial class register : Form
    {
        public register()
        {
            InitializeComponent();
        }

    //New thread for Form2
    public static void ThreadProc()
    {
        //New Form
        Application.Run(new Form2());

    }

    //Close Form
    private void Registro_FormClosing(Object sender, FormClosingEventArgs e) 
    {
        regresoForma();
    }

    private void regresoForma()
    {
        //New thread
        System.Threading.Thread nuevoRegistro2 = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));

        //Start thread
        nuevoRegistro2.Start();

        //Close this form
        this.Close();
    }


    private void button1_Click(object sender, EventArgs e)
    {

    }
}
}
4

2 に答える 2

1

代わりにこれを使用することをお勧めします。マルチスレッドはまったく必要ありません。

private void regresoForma()
{
    //Hide this form
    this.Visible=false;

    //Start Form2 but as a dialog 
    //i.e. this thread will be blocked til Form2 instance closed
    (new Form2()).ShowDialog();

    //Reshow this form
    this.Visible=true;
}
于 2013-09-07T18:57:59.917 に答える
0

各フォームをまったく新しいプロセスとして確立する必要がない限り、フォームをすべて非同期にする必要がある場合は、BackgroundWorker を使用して新しいフォームを表示することをお勧めします。WinForms を使用している場合。WPF を使用している場合は、Dispatcher を使用して新しいフォームを作成する必要があります。

それは本当にフォームの流れに依存します。

個人的には、完全に必要な場合を除き、新しいスレッドを作成しないようにしています。完全に新しいアプリケーションを呼び出す場合を除き、上記の方法のいずれかを使用して作成します。

于 2013-09-07T06:12:31.737 に答える