线程没有用c#关闭

时间:2014-01-02 18:26:11

标签: c# multithreading

我这里有点问题。

我启动一个线程在Windows窗体上显示时间,但是当我关闭时,处理程序“onclosed”或“onclosing”不起作用Application.Exit();

线程一直在运行。

代码:

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

2 个答案:

答案 0 :(得分:2)

您需要将线程变量保存在以后可以访问它以停止线程的位置。或者您需要一个对象来同步两个线程。或者(我认为这将是最好的选择)你单独留下线程并使用System.Windows.Forms.Timer来显示时间。

答案 1 :(得分:1)

Application.ExitThread();只是告诉主消息循环停止处理。但是您创建的线程是与主消息循环完全独立的线程。它也是一个前台线程,因为仍然有一个运行应用程序的前台线程不会结束。

虽然有几种方法可以解决这个问题并阻止其他线程执行,但你甚至不应该这样做。首先,您没有使用正确的工具。而不是创建一个线程,以便它可以花费99.99%的时间在一段时间内休眠,只需使用Timer。它可以在一个设置的时间间隔内运行一些代码(如果你使用表单计时器,甚至在主线程中运行该代码)。您可以更轻松地使用它,并且不会导致创建任何需要关闭或可以保持应用程序运行的新线程。