Dietrich Prg
Dietrich Prg

Reputation: 84

Thread doesn't close with c#

I have a little problem here.

I start a thread to show time on windows form, but when I close, the handler " onclosed " or " onclosing " dont work Application.Exit();

the thread keeps running.

the code:

    private void frm_agenda_Load(object sender, EventArgs e)
    {
        Thread t = new Thread(new ThreadStart(disparar_time));
        t.Start();
    }

    private void disparar_time()
    {
        while (true)
        {
            time(lbl_time);
            Thread.Sleep(1000);
        }
    }

    public delegate void delegade_time(Label lbl);
    private void time(Label lbl)
    {
        if (InvokeRequired)
        {
            try
            {
                Invoke(new delegade_time(time), lbl_time);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        else
        {
            try
            {
                DateTime date = DateTime.Now;
                lbl.Text = date.ToLongDateString() + " " + date.ToLongTimeString();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

    private void frm_agenda_FormClosing(object sender, FormClosingEventArgs e)
    {
        Application.ExitThread();
    }

Upvotes: 0

Views: 670

Answers (2)

Servy
Servy

Reputation: 203802

Application.ExitThread(); simply tells the main message loop to stop processing. But the thread you create is an entirely separate thread from the main message loop. It's also a foreground thread, and since there is still a foreground thread running the application won't end.

While there are several ways you could address this and stop the other thread from executing, you shouldn't even do that. You're not using the right tool for the job in the first place. Rather than creating a thread just so that it can spend 99.99% of it's time sleeping for a set interval of time, just use a Timer instead. It can run some code (and if you use the forms timer, even run that code in the main thread for you) in a set interval. It will be easier for you to work with, and won't result in the creation of any new threads that need to be closed or that could keep the application running.

Upvotes: 1

nvoigt
nvoigt

Reputation: 77285

You need to keep your thread variable in a place where you can access it later to stop the thread. Or you need an object to syncronize the two threads. Or (and I think that would be the best option) you leave threading alone for a while and use a System.Windows.Forms.Timer to display the time.

Upvotes: 2

Related Questions