程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> Dotnet定時器使用實例詳解

Dotnet定時器使用實例詳解

編輯:關於C#

下面代碼都是實現每過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;
}
}

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();
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved