在 ASP.NET 中是可以有定時器的,并且不是 JavaScript 定時器,而是伺服器端的定時器,由于這些定時器在 ASP.NET 中應用并不多見,是以我們并不詳細介紹,隻是介紹基本應用。
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Threading" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public class CFoo
{
public static Label lb;
public void Go()
{
TimerCallback timerDelegate = new TimerCallback(Working);
AutoResetEvent autoEvent = new AutoResetEvent(false);
System.Threading.Timer workingTimer = new System.Threading.Timer(timerDelegate, autoEvent, 2000, 1000);
autoEvent.WaitOne(5000, false);
workingTimer.Dispose();
}
static void Working(object stateInfo)
//AutoResetEvent autoEvent = (AutoResetEvent)stateInfo; //沒有使用,這裡寫出來僅說明參數 stateInfo 的用途
if (lb.Text.Length > 0)
{
lb.Text += "<br />" + DateTime.Now.ToString();
}
else
lb.Text = DateTime.Now.ToString();
}
void Page_Load(object sender, EventArgs e)
lbStart.Text = DateTime.Now.ToString();
CFoo foo = new CFoo();
CFoo.lb = lbTimer;
foo.Go();
lbEnd.Text = DateTime.Now.ToString();
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET Threading-定時器</title>
</head>
<body>
<form id="form1" runat="server">
<div><asp:Label ID="lbStart" runat="server"></asp:Label></div>
<hr />
<div><asp:Label ID="lbTimer" runat="server"></asp:Label></div>
<div><asp:Label ID="lbEnd" runat="server"></asp:Label></div>
</form>
</body>
</html>
System.Threading 是名稱空間,不過 System.Threading.Timer 仍不能簡寫為 Timer,因為會和 System.Web.UI.Timer 混淆。
TimerCallback 處理來自 Timer 的調用的方法,參數為方法名稱。
AutoResetEvent 通知正在等待的線程已發生事件。若要将初始狀态設定為終止,則參數為 true;若要将初始狀态設定為非終止,則參數為 false。
System.Threading.Timer 第三個參數表示定時器多少毫秒後開始(此時回調函數會立即被執行),第四個參數表示定時器開始後的觸發間隔。
WaitOne 阻塞線程,等待信号。第一個參數為等待的毫秒數,第二個參數若為 true,則表示等待之前先退出上下文的同步域。
Working 回調函數。參數必不可少,必須是 static 函數。
Timeout.Infinite 在上述程式中并未被提及,表示無限長的時間。