下面代码都是实现每过2秒刷新显示当前数据库的对象,分别使用三种计时器:
1、Winform 的计时器(System.Windows.Forms.Timer)
Forms.Timer为单线程计时器,依赖当前窗体.使用最简单:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
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;
}
}
2、服务器的计时器(System.Timers.Timer)
该计时器为多线程,不依赖窗体,是从线程唤醒,因为与当前窗体不在同一个线程中 ,所以无法操作当前窗体控件.可将计时器的SynchronizingObject的属性为this,表明线程与当前窗体同步,否则使用委托实现.
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
public partial class Form1 : Form
{
System.Timers.Timer t;
delegate void BindDataSourceCallback(DataSet ds);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new System.Timers.Timer();
t.Interval = 2000;//每2秒刷新一次datagridview
t.Enabled = true;
t.Elapsed += new System.Timers.ElapsedEventHandler(timersTimer_Elapsed);
t.Start();
}
private void timersTimer_Elapsed(object source, System.Timers.ElapsedEventArgs 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();
BindDataSourceCallback temp = new BindDataSourceCallback(bindData);
this.Invoke(temp, new object[] { ds });
}
private void bindData(DataSet ds)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
dataGridView1.Refresh();
}
}
3、线程计时器(System.Threading.Timer)
Threading.Timer也属于多线程计时器,需要使用委托来调用.
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
public partial class Form1 : Form
{
System.Threading.Timer t;
delegate void BindDataSourceCallback(DataSet ds);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new System.Threading.Timer(
new System.Threading.TimerCallback(timersTimer_Elapsed),
null, 0, 2000);//间隔2秒
}
private void timersTimer_Elapsed(object source)
{
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();
BindDataSourceCallback temp = new BindDataSourceCallback(bindData);
this.Invoke(temp, new object[] { ds });
}
private void bindData(DataSet ds)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
dataGridView1.Refresh();
}
}