2016-08-21 104 views
0

我做了一個窗口窗體應用程序,按下按鈕每5分鐘執行一次該方法,然後再按一次停止這樣做......但它仍然繼續執行該方法,即使我打電話給停止方法從計時器。爲什麼我不能停止我的計時器

System.Timers.Timer t = new System.Timers.Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); 
t.AutoReset = true; 
t.Elapsed += new System.Timers.ElapsedEventHandler(my_method); 
if (start == false) 
{ 
    t.Start(); 
    start = true; 
    Checkbutton.Text = "End"; 
} 
else 
{ 
    t.Stop(); 
    t.AutoReset = false; 
    Checkbutton.Text = "Begin"; 
    MessageBox.Show("Auto Check Stop!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); 
} 
+4

是不是你創建這個功能的新的計時器每次?將Timer t作爲你的類的私有變量,並且在開始時移動t = new Timer stuff == false條件;就在t.Start()之前。 – Developer

回答

2

您正在實例化一個新的Timer類實例,每次點擊您提供給用戶的按鈕以控制計時器的啓動/停止狀態。 你應該實例化它只有一次內聯,同時將其聲明爲成員變量或內部的表單類的構造函數。然後保持通話的按鈕單擊事件處理程序中開始/停止API如下圖所示的代碼來改變它的基礎上的start標誌值聲明:

public partial class Form1 : Form 
{ 
     System.Timers.Timer t = new System.Timers.Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); 
     bool start == false; 

     public Form1() 
     { 
      InitializeComponent(); 
      t.AutoReset = true; 
      t.Elapsed += new System.Timers.ElapsedEventHandler(my_method); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      if (start == false) 
      { 
       t.Start(); 
       start = true; 
       Checkbutton.Text = "End"; 
      } 
      else 
      { 
       t.Stop(); 
       t.AutoReset = false; 
       Checkbutton.Text = "Begin"; 
       MessageBox.Show("Auto Check Stop!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); 
      } 
     } 
} 
0

您的計時器需要限定在函數之外。將前三行移到該函數之外。

0

因爲每次執行問題中的代碼,你會得到一個新的計時器。

想必你的代碼做這個:

  1. 構造一個新的計時器
  2. 由於starttrue,你下一次執行它啓動定時器
  3. ,構造一個新的計時器(從獨立第一個)
  4. 由於startfalse你問這個新的計時器停止,但它從未開始

如果您想停止之前啓動的計時器,則需要存儲對其的引用,以便您可以訪問相同的計時器。

通常你會將它存儲在周圍類的字段中。還要確保你只構造一次定時器。

相關問題