2011-11-17 32 views
1

タイマーを停止した後も、イベントハンドラーが呼び出しを停止することはありません。私のコードに何か問題がありますか?助けてください!C#タイマー停止後のイベントハンドラーの停止

私はあなたたちが私にいくつかの助けを行うことができれば、それが防止されますので、書かれたが、タイマーを起動しませんよう、3つの異なる方法で(、このコード

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:\cygwin\var\spool\sms\outgoing\sms.txt"); 

         TextWriter tw = new StreamWriter(@"C:\\Test.txt"); 
         { 
          tw.WriteLine("To: 6592786618\n"); 
          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:\cygwin\var\spool\sms\outgoing\Test.txt")); 
         { 
          tw.WriteLine("To: 6592786618\n"); 
          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:\cygwin\var\spool\sms\outgoing\sms.txt"); 
     TextWriter tw = new StreamWriter(@"C:\\Test1.txt"); 
     { 
      tw.WriteLine("To: 6592786618\n"); 
      tw.WriteLine("\n"); 
      tw.WriteLine("\n" + strName + @" has just left at " + DateTime.Now); 
      tw.Close(); 
     } 
    } 
+0

他の何かがそれを呼びますか? –

+3

"timer2.Interval = 2000; // 30分間隔" - それほどではありません。 2秒です。 – Joe

+0

間に何が起こるのですか?あなたは同じタイマーのインスタンスから退会していますか? –

答えて

2

timer2がインスタンス変数の場合、問題はtimer2というローカル変数を作成して起動することです。次に、ローカルスコープtimer2ではなく、メンバ変数timer2を停止します。ローカルスコープtimer2は、ガベージコレクタが処理を終えるまで実行を続けます。

私はtimer2がインスタンス変数であることを確信しています。そうでなければ、それに対する他の参照はコンパイルされません。ループ内にtimer2を作成しているので、おそらくそれらのボートロードが作成されていることに注意してください。ガベージコレクタがそれらを悲惨さから排除するまで、すべてのものが楽しく消えます。

編集:ここでは、フォーム内での使用例を示します。

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

あなたは、単にあなたのフォームデザイン上にタイマーコンポーネントをドロップしている場合は、その初期化は、この例のようにInitializeComponents方法であなたのために書かれています。これ以外にも、私ははるかに助けることはできません。私はあなたがタイマーを使用しようとしている方法にいくつかの構造的な問題があると思う。すべての開始と停止、特にforループのtimer2は、それがあなたに多くのトラブルや頭痛を引き起こすようです。

+0

私はちょっとあなたを少し得る。どのように変数を作成するのですか? –

+0

コンストラクタで一度timer2を作成するか、オブジェクトインスタンスを初期化します。そして、すべてのものがその単一インスタンスを参照します。フォーム配管は、フォームクラスにどのように組み込んでいるかによって、あなたのために作成しているかもしれません。 – hatchet

+0

私のtimer1が見えますか? Timer1_Tickイベントハンドラをtimer1が呼び出されたときにどうやって呼び出すことができたのか不思議です。そして、timer1をコメントアウトしても "驚くほど" Timer1_Tickが呼び出されます。どうして? –

-1

:)をしてください、内部の私の全体のコードを含めました)時間が経過する前に。あなたの本当の問題については

//Stop timer2 
timer2.Stop(); 
timer2.Tick -= timer2_Tick; 

...私たちはあなたのコードの残りの部分はあなたを助けるために参照する必要があります。

+0

...コメントにする必要があります。 –

1

あなたのストップコードはと良いだろう。

+0

私は残りのコードを含めました。どうぞご覧ください。 –

+0

あなたのRFIDのものがなければ、私は本当に何かをテストすることはできません。また、ソリューションではない場合は、ソリューションとして回答を受け入れることは好ましくありません。 1)あなたはtimer1のtickの中からtimer2を起動していますが、これは追跡や維持が容易ではありません。 2)elseブロックでタイマー2を停止していますが、一部のdbクエリとメッセージボックスの後にタイマー2を停止していることが分かっている場合は、ブロックの先頭でタイマー2を実行します。 3.)いくつかのブレークポイントを設定し、フォロースルーします。ここには答えがあります。その魔法ではありません – rfmodulator

2

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スレッドをブロックし、それらが解除されるまで追加のタイマーティックを防ぐので、そこに残したくありません。

+0

ありがとうございます。私はコードを何度もチェックしましたが、それでも問題を見つけることはできません。 –

+0

私はそれを今得ました。しかし、同じことが私が実際にForm_Loadでtimer1をコメントアウトするtimer1についても起こりますが、まだtimer1_Tickイベントハンドラは呼び出されています。なぜこれはそうですか? –

+0

System.Windows.Forms.Timerを削除して取得しました。timer2 = new System.Windows.Forms.Timer(); ありがとうございました! –

関連する問題