定时器使用实例
3、线程计时器(System.Threading.Timer)
Threading.Timer也属于多线程计时器,需要使用委托来调用.
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();
}
} |