下面代码都是实现每过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;
}
}
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();
}
}
|