我正在制作一个程序,它必须每 30 或 60 分钟检查一次数据库,并在 Windows 窗体界面中显示结果(如果有)。当然,from 提供访问的其他功能在执行数据库检查时应该仍然可用。为此,我使用了 System.Timers.Timer,它在与 UI 不同的线程上执行一个方法(如果使用这种方法有问题,请随时发表评论)。我写了一个小而简单的程序来测试热点的工作,只是注意到我不能真正将间隔设置为超过 ~ 1 分钟(我需要 30 分钟到一个小时)。我想出了这个解决方案:
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 方法,似乎有点没用。有没有办法实际设置更长的计时器间隔?