C#如何及时停止线程?

时间:2013-09-13 14:50:54

标签: c# multithreading timer

我有一个包含计时器的用户控件。当timer事件运行时,它将调用一些线程。

用户控制

class MyControl
{
    public Timer iTime
    {
        get;
        set;
    }

    Timer tmr;

    public MyControl
    {
    tmr = new Timer();
    }

    // Some Properties
}
}

主要表格

class MyForm
{
     Thread thd;

     MyControl cls = new MyClass();
     cls.iTime.Tick += new EventHandler(iTime_Tick);

     void iTime_Tick(object sender, EventArgs e)
     {
         thd = new Thread(delegate() { doWork(1); });
         thd.Start();

         thd = new Thread(delegate() { doOtherJob(); });
         thd.Start();
     }

     delegate void notif(int Param1);

     void Job(int Param1)
     {
         if (this.InvokeRequired) 
         {
            notif handler = new notif(notifParam);
            this.Invoke(handler, new object[] { Param1 });
         }
         else
         {
        // Other Process
         }
     }

     private void Logout()
     {
        cls.iTime.Stop();
        cls.iTime.Enabled = false;
        cls.iTime.Tick -= new EventHandler(iTime_Tick);

        thd.abort();
        thd.join();
     }
}

如何在计时器中终止线程?当我取消订阅计时器事件甚至关闭表格时,线程仍在运行。

1 个答案:

答案 0 :(得分:2)

处理表单对您的主题没有影响。

您的代码显然不完整(例如MyControl cls = new MyClass();,我们不知道doWorkdoOtherJob是什么),但我怀疑部分问题是您只有单线程变量。

每次计时器滴答时,您都会thd = new Thread 两次。如果您的计时器滴答十次,那么thd指向您最近的线程,但可能还有19个其他线程仍在运行,其中任何一个都可能使您的应用程序保持活动状态。

可能有用的一件事是在您创建的线程上明确设置.IsBackgroundtrue,因为这会鼓励它们在您的UI线程关闭时终止。但是,我建议以这种方式创建这么多线程可能是一个有效的模型,你最好修改你的设计只运行一两个工作线程,而不是踢几十个。