下面代碼都是實現每過2秒刷新顯示當前數據庫的對象,分別使用三種計時器:
1、Winform 的計時器(System.Windows.Forms.Timer)
Forms.Timer為單線程計時器,依賴當前窗體.使用最簡單:
public partial class Form1 : Form
{
System.Windows.Forms.Timer t;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new System.Windows.Forms.Timer();
t.Interval = 2000;//間隔時間
t.Enabled = true;
t.Tick += new EventHandler(timersTimer_Elapsed);
t.Start();
}
private void timersTimer_Elapsed(object source, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(
"select * from sysobjects order by newid()",
"server=.;uid=sa;pwd=sa;database=master;");
sda.Fill(ds);
sda.Dispose();
dataGridView1.DataSource = ds.Tables[0].DefaultVIEw;
}
}