• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C# timer定时器的用法实例

OC/C/C++ 水墨上仙 2341次浏览

通过Timer可以定期调用指定的代码,C#中的Timer可以每隔几秒或者几分钟定期指定一个指定的函数。如果我们需要定时监控重要程序的状态或者变量状态都非常有用。Timer被定义在System.Timers命名空间内。

举例:

下面这个C#范例是定义了一个静态类,这意味着它不能有实例成员或字段。它包括System.Timers命名空间,它定义了一个定时执行的函数,每隔3秒钟向List列表中添加一个当前日期。

using System;
using System.Collections.Generic;
using System.Timers;

public static class TimerExample // In App_Code folder
{
    static Timer _timer; // From System.Timers
    static List<DateTime> _l; // Stores timer results
    public static List<DateTime> DateList // Gets the results
    {
	get
	{
	    if (_l == null) // Lazily initialize the timer
	    {
		Start(); // Start the timer
	    }
	    return _l; // Return the list of dates
	}
    }
    static void Start()
    {
	_l = new List<DateTime>(); // Allocate the list
	_timer = new Timer(3000); // Set up the timer for 3 seconds
	//
	// Type "_timer.Elapsed += " and press tab twice.
	//
	_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
	_timer.Enabled = true; // Enable it
    }
    static void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
	_l.Add(DateTime.Now); // Add date on each timer event
    }
}


注意:这个C#类没有输出,必须通过外部调用

下面是一个通过.aspx调用timer的实例


using System;
using System.Web;
using System.Web.UI;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
	HttpResponse r = Response; // Get reference to Response
	foreach (DateTime d in TimerExample.DateList) // Get the timer results
	{
	    r.Write(d); // Write the DateTime
	    r.Write("<br/>"); // Write a line break tag
	}
    }
}

这段C#代码调用上面定义的TimerExample类,在浏览器中输出时间,如果你不断的刷新网页,会不断的有新的项目加入


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C# timer定时器的用法实例
喜欢 (0)
加载中……