ASP.NET Threading-定时器

作者:vkvi 来源:ITPOW(原创) 日期:2007-8-29

在 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>
    <hr />
    <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 在上述程序中并未被提及,表示无限长的时间。


相关文章