我正在製作一個程序,它必須每30或60分鐘檢查一次數據庫,並在Windows窗體界面中顯示結果(如果有)。當然,在執行數據庫檢查時,from提供的其他函數仍應該可用。爲此,我使用System.Timers.Timer,它在UI的另一個線程上執行一個方法(如果使用這種方法出現問題,請隨時評論它)。我寫了一個小而簡單的程序來測試熱門的工作,但只注意到我無法真正將Interval設置爲1分鐘以上(我需要30分鐘到1小時)。我想出了這個解決方案:是否有其他方法來設置長計時器間隔
public partial class Form1 : Form
{
int s = 2;
int counter = 1; //minutes counter
System.Timers.Timer t;
public Form1()
{
InitializeComponent();
t = new System.Timers.Timer();
t.Elapsed += timerElapsed;
t.Interval = 60000;
t.Start();
listBox1.Items.Add(DateTime.Now.ToString());
}
//doing stuff on a worker thread
public void timerElapsed(object sender, EventArgs e)
{
//check of 30 minutes have passed
if (counter < 30)
{
//increment counter and leave method
counter++;
return;
}
else
{
//do the stuff
s++;
string result = s + " " + DateTime.Now.ToString() + Thread.CurrentThread.ManagedThreadId.ToString();
//pass the result to the form`s listbox
Action action =() => listBox2.Items.Add(result);
this.Invoke(action);
//reset minutes counter
counter = 0;
}
}
//do other stuff to check if threadid`s are different
//and if the threads work simultaneously
private void button1_Click(object sender, EventArgs e)
{
for (int v = 0; v <= 100; v++)
{
string name = v + " " + Thread.CurrentThread.ManagedThreadId.ToString() +
" " + DateTime.Now.ToString(); ;
listBox1.Items.Add(name);
Thread.Sleep(1000); //so the whole operation should take around 100 seconds
}
}
}
不過這樣一來,正在引發Elapsed事件,並呼籲timerElapsed方法每分鐘一次,這似乎有點沒用。有沒有辦法實際設置更長的定時器間隔?
我看不到問題。以毫秒錶示1小時(3600000)適合'int'。 – Tudor
哈哈哈哈哈哈!確實如此,我記得在某個地方讀書時,不可能設置這樣的間隔,所以我從來沒有想過嘗試。謝謝:) –