2、服務器的計時器(System.Timers.Timer)
該計時器為多線程,不依賴窗體,是從線程喚醒,因為與當前窗體不在同一個線程中 ,所以無法操作當前窗體控件.可將計時器的SynchronizingObject的屬性為this,表明線程與當前窗體同步,否則使用委托實現.
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也屬於多線程計時器,需要使用委托來調用.
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();
}
}