在System.Threading命名空间中存在Timer类与对应的TimerCallback委托,它可以在后台线程中执行一些长期的定时操作,使主线程不受干扰。
Timer类中最常用的构造函数为 public Timer( timerCallback , object , int , int )
timerCallback委托可以绑定执行方法,执行方法必须返回void,它可以是无参数方法,也可以带一个object参数的方法。
第二个参数是为 timerCallback 委托输入的参数对象。
第三个参数是开始执行前等待的时间。
第四个参数是每次执行之间的等待时间。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Timer_Callback
{
class Program
{
static void Main(string[] args)
{
ThreadPool.SetMaxThreads(1000, 1000);
TimerCallback callback = new TimerCallback(ThreadPoolMessage);
Timer t = new Timer(callback, "Hello Jack!", 500, 1000);
Console.ReadKey();
}
static void ThreadPoolMessage(object data)
{
int a, b;
ThreadPool.GetAvailableThreads(out a, out b);
string message = string.Format("{0}\n CurrentThreadId is {1}\n " +
" CurrentThread isBackground:{2}\n WorkerThreads is:{3}" +
" CompletionPortThreadId is:{4}\n",
data + "Time now is "+DateTime.Now.ToLongTimeString(),
Thread.CurrentThread.ManagedThreadId,
Thread.CurrentThread.IsBackground.ToString(),a, b);
Console.WriteLine(message);
}
}
}