c#计时器停止后停止事件处理程序



为什么我的eventandler从来没有停止调用,即使我停止了定时器?我的代码有问题吗?请帮助!

我已经包含了我的整个代码里面,如果你们能做我一些帮助请:)

private void Form1_Load(object sender, EventArgs e)
    {
        //Start system
        axInRFIDCtrl1.SelectReaderFeig();
        axInRFIDCtrl1.FEInit();
        short sResult = axInRFIDCtrl1.FEOpen();
        //MessageBox.Show(sResult.ToString());
        //Start timer1
        System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
        timer1.Interval = 1000;
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Enabled = true;
        timer1.Start();
        Console.ReadLine();
    }
    public void timer1_Tick(object sender, EventArgs e)
    {
        //Get ID
        string strTagIds = string.Empty;
        int iState = 0;
        axInRFIDCtrl1.FESelect(ref strTagIds, ref iState);
        string[] strTagID = strTagIds.Split(new char[] { '|' });
        string strTag = strTagID[0];
        textBox1.Text = strTag;
        //Connection to datebase
        string c1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Project.mdb";
        OleDbConnection con = new OleDbConnection(c1);
        //Bind button
        string txt = textBox1.Text;
        string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Project.mdb";
        string strSqlStatement = string.Empty;
        strSqlStatement = "SELECT * FROM jiahe WHERE [Tag ID] = '" + txt + "'";
        OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
        OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSqlStatement, objConnection);
        DataSet ds = new DataSet();
        objAdapter.Fill(ds);
        DataTable dt = ds.Tables[0];
        dataGridView1.DataSource = dt.DefaultView;
        if (dt.Rows.Count == 1)
        {
            string strLine = string.Empty;
            string strUser = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                string strTags = dr["Tag ID"].ToString();
                strUser = dr["User"].ToString();
                string strAge = dr["Age"].ToString();
                string strPhoneNumber = dr["Phone Number"].ToString();
                // prepare command string
                string selectString = @"SELECT Status FROM jiahe where [Tag ID] = '" + textBox1.Text + "'";
                // 1. Instantiate a new command with command text only
                OleDbCommand cmd = new OleDbCommand(selectString, objConnection);
                // 2. Set the Connection property
                cmd.Connection.Open();
                // 3. Call ExecuteScalar to send command
                string str = cmd.ExecuteScalar().ToString();
                cmd.Connection.Close();
                foreach (DataRow datarow in dt.Rows)
                {
                    //string strName = string.Empty;
                    strName = datarow["User"].ToString();
                    if (str.Length == 2 || str.Length == 0)
                    {
                        // prepare command string
                        string updateString = @"update jiahe set Status = 'OUT' where [Tag ID] = '" + textBox1.Text + "'";
                        // 1. Instantiate a new command with command text only
                        OleDbCommand cmd1 = new OleDbCommand(updateString, objConnection);
                        // 2. Set the Connection property
                        cmd1.Connection.Open();
                        // 3. Call ExecuteNonQuery to send command
                        str = cmd1.ExecuteNonQuery().ToString();
                        cmd1.Connection.Close();
                        //write text file to outgoing spool
                        //TextWriter tw = new StreamWriter(@"C:cygwinvarspoolsmsoutgoingsms.txt");
                        TextWriter tw = new StreamWriter(@"C:\Test.txt");
                        {
                            tw.WriteLine("To: 6592786618n");
                            tw.WriteLine("n");
                            tw.WriteLine("n" + strName + @" has just left at " + DateTime.Now);
                            tw.Close();
                        }
                        MessageBox.Show(strName + " has left the house.");
                        //Start timer2
                        System.Windows.Forms.Timer timer2 = new System.Windows.Forms.Timer();
                        timer2.Interval = 1000 * 60 * 30; //30 mins interval
                        timer2.Tick += new EventHandler(timer2_Tick);
                        timer2.Enabled = true;
                        timer2.Start();
                        //Log to listbox
                        // Set the selection mode to multiple and extended.
                        listBox1.SelectionMode = SelectionMode.MultiExtended;
                        listBox1.BeginUpdate();
                        listBox1.Items.Add(DateTime.Now + " - " + strName + " > OUT");
                        listBox1.EndUpdate();
                        //Log event to log file
                        string cs = "Minder+Finder Event Log";
                        EventLog elog = new EventLog();
                        if (!EventLog.SourceExists(cs))
                        {
                            EventLog.CreateEventSource(cs, cs);
                        }
                        elog.Source = cs;
                        elog.EnableRaisingEvents = true;
                        elog.WriteEntry(DateTime.Now + " - " + strName + " > OUT");
                    }
                    else
                    {
                        // prepare command string
                        string updateString = @"update jiahe set Status = 'IN' where [Tag ID] = '" + textBox1.Text + "'";
                        // 1. Instantiate a new command with command text only
                        OleDbCommand cmd1 = new OleDbCommand(updateString, objConnection);
                        // 2. Set the Connection property
                        cmd1.Connection.Open();
                        // 3. Call ExecuteNonQuery to send command
                        str = cmd1.ExecuteNonQuery().ToString();
                        cmd1.Connection.Close();
                        //write text to outgoing spool
                        TextWriter tw = new StreamWriter(@"C:\Test.txt");
                        //using (TextWriter tw = File.CreateText("C:cygwinvarspoolsmsoutgoingTest.txt"));
                        {
                            tw.WriteLine("To: 6592786618n");
                            tw.WriteLine("n");
                            tw.WriteLine("n" + strName + @" has just returned home at " + DateTime.Now);
                            tw.Close();
                        }
                        MessageBox.Show(strName + " has returned home.");
                        //Stop timer2
                        timer2.Tick -= timer2_Tick;
                        timer2.Enabled = false;
                        timer2.Stop();
                        //Log to listbox
                        // Set the selection mode to multiple and extended.
                        listBox1.SelectionMode = SelectionMode.MultiExtended;
                        listBox1.BeginUpdate();
                        listBox1.Items.Add(DateTime.Now + " - " + strName + " > IN");
                        listBox1.EndUpdate();
                        //Log event to log file
                        string cs = "Minder+Finder Event Log";
                        EventLog elog = new EventLog();
                        if (!EventLog.SourceExists(cs))
                        {
                            EventLog.CreateEventSource(cs, cs);
                        }
                        elog.Source = cs;
                        elog.EnableRaisingEvents = true;
                        elog.WriteEntry(DateTime.Now + " - " + strName + " > IN");
                    }
                }
            }
        }
        else
        {
            timer1.Enabled = false;
        }
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();
        form2.ShowDialog();
    }
    private void button2_Click(object sender, EventArgs e)
    {
        Form3 form3 = new Form3();
        form3.ShowDialog();
    }
    public void timer2_Tick(object sender, EventArgs e)
    {
        MessageBox.Show(strName + " has left");
        //write text file to outgoing spool
        //TextWriter tw = new StreamWriter(@"C:cygwinvarspoolsmsoutgoingsms.txt");
        TextWriter tw = new StreamWriter(@"C:\Test1.txt");
        {
            tw.WriteLine("To: 6592786618n");
            tw.WriteLine("n");
            tw.WriteLine("n" + strName + @" has just left at " + DateTime.Now);
            tw.Close();
        }
    }

如果timer2是一个实例变量,那么问题是您正在创建一个也称为timer2的局部变量并启动它。然后停止成员变量timer2,而不是局部作用域timer2。局部作用域timer2将一直触发,直到垃圾收集器处理它。

我很确定timer2是一个实例变量,否则对它的其他引用将无法编译。还需要注意的是,由于是在循环中创建timer2,因此可能会创建一船的timer2,并且它们都愉快地继续工作,直到垃圾收集器将它们从痛苦中解脱出来。

编辑:这是一个在表单中使用的相当简单的例子。

http://www.java2s.com/Code/CSharp/GUI-Windows-Form/GUIandtimer.htm

如果您只是将计时器组件放到表单设计中,那么初始化将在InitializeComponents方法中为您编写,如下例所示。除了这个,我也帮不上什么忙了。我认为你使用计时器的方式存在一些结构性问题。所有的开始和停止,特别是在for循环中的timer2,似乎会给您带来很多麻烦和头痛。

如果您停止定时器(通过调用Stop()或通过设置Enabled = false),那么它将不会再次触发。我从来没有看到过停止计时器调用事件处理程序的情况。如果事件处理程序在禁用计时器后仍然被调用,那么要么是其他代码正在调用它,要么是某些东西正在重新启用计时器。

还请注意,如果事件处理程序当前正在执行,停止计时器将不会中止事件。它也不会阻止任何挂起的事件。虽然这应该不是System.Windows.Forms.Timer的问题,因为它的事件处理程序总是在GUI线程上执行。

如果我是你,我会非常仔细地检查代码,查看所有启用或禁用计时器的地方。我怀疑你会发现你的代码中有什么东西重新启用定时器。

看到你发布的代码后编辑:

可能的问题是,在您的计时器事件处理程序中,您有以下内容:

System.Windows.Forms.Timer timer2 = new System.Windows.Forms.Timer();
// code that initializes and enables timer

创建了一个局部timer2变量,它将不同于窗体作用域中的timer2(我假设,因为您暗示代码编译,并且您在单独的作用域中引用timer2)。您最终创建了一个新的计时器,但是禁用计时器的代码引用了表单范围timer2。所以发生的事情是,你创建了很多不同的计时器,它们中的每一个最终调用相同的事件处理程序。

我希望你在事件处理程序中调用MessageBox.Show只是为了调试目的。你不希望把它们留在那里,因为它们会阻塞UI线程,并且会阻止额外的计时器滴答,直到它们被解除。

你的停止代码最好是:

//Stop timer2
timer2.Stop();
timer2.Tick -= timer2_Tick;
关于你真正的问题……我们需要看到你的代码的其余部分来帮助你。

这段代码从未触发计时器,因为它在时间结束之前(通过三种不同的方式)被阻止了。

相关内容

  • 没有找到相关文章

最新更新