简体   繁体   中英

Stop thread from another thread and Form

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)
    {

    }
}
}

I suggest you use this instead and you don't need multi-threading at all:

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;
}

Unless you need to have each form establish itself as an entirely new process, I would recommend using BackgroundWorker to display the new forms if you need them to all be asynchronous. If you're using WinForms. If you are using WPF, You'll need to use Dispatcher to create the new forms.

It really depends on the flow of your forms.

I personally try to avoid creating new threads unless it is absolutely one hundred percent necessary, and I use one of the above mentioned methods to do so unless I'm calling a completely brand new application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM