转timer

本文介绍了如何在ASP.NET中实现服务器端定时器,通过C#代码创建了一个定时任务示例,该任务每隔一段时间更新页面上的时间戳。

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

转载于:https://www.cnblogs.com/zwei1121/archive/2007/09/07/886123.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值