System.Threading.Timer 非javascript的WEB Timer使用

來源:互聯網
上載者:User

在 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 在上述程式中並未被提及,表示無限長的時間。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.