最初我的代码有Timer
,它会不断ping服务器以查看它是否已连接。但是,我还有一个Timer
来显示当前时间。这就是它原来的样子:
public Main()
{
/* let's check if there is a connection to the database */
isDbAvail = new Timer();
isDbAvail.Interval = 8000;
isDbAvail.Tick += new EventHandler(isOnline);
isDbAvail.Start();
/* the clock */
clock = new Timer();
clock.Interval = 1000;
clock.Tick += new EventHandler(clockTimer_Tick);
clock.Start();
}
private void isOnline(object sender, EventArgs e)
{
Connection connection = new Connection();
changeStatus(connection.isDbAvail());
}
private void clockTimer_Tick(object sender, EventArgs e)
{
clock.Text = DateTime.Now.ToString("MMM dd, yyyy HH:mm:ss");
}
到目前为止,一切工作正常,除了检查数据库时,整个用户界面将冻结,并将滞后约3秒。我做了一些研究,发现了BackgroundWorker并将所有内容改为:
public Main()
{
isDbAvail = new BackgroundWorker();
isDbAvail.DoWork += isOnline;
/* the clock */
clock = new Timer();
clock.Interval = 1000;
clock.Tick += new EventHandler(clockTimer_Tick);
clock.Start();
}
private void isOnline(object sender, DoWorkEventArgs e)
{
while (true)
{
Thread.Sleep(8000);
Connection connection = new Connection();
changeStatus(connection.isDbAvail());
}
}
当我运行时,没有任何反应,我也没有错误。我非常确定这里有一些非常重要的东西,我似乎无法掌握。
答案 0 :(得分:0)
添加
isDbAvail.RunWorkerAsync();
之后
isDbAvail.DoWork
行