多线程编程学习笔记(五)

多线程编程学习笔记(五)
处理周期事件
1、System.WinForms.Timer
Timer的Tick事件代码:
Interlocked.Increment(ref _count);

2、ThreadPool
A.生成WaitOrTimerCallback事例
B.生成一个同步对象
C.添加到线程池

例1:
/*RegisterWaitForSingleObject
下面的示例演示了几种线程处理功能。

使用 RegisterWaitForSingleObject 将需要执行的任务以 ThreadPool 线程的方式排队。
使用 AutoResetEvent 发出信号,通知执行任务。
用 WaitOrTimerCallback 委托处理超时和信号。
用 RegisteredWaitHandle 取消排入队列的任务。
*/
using System;
using System.Threading;

// TaskInfo contains data that will be passed to the callback
// method.
public class TaskInfo {
    public RegisteredWaitHandle Handle = null;
    public string OtherInfo = "default";
}

public class Example {
    public static void Main(string[] args) {
        // The main thread uses AutoResetEvent to signal the
        // registered wait handle, which executes the callback
        // method.
        AutoResetEvent ev = new AutoResetEvent(false);

        TaskInfo ti = new TaskInfo();
        ti.OtherInfo = "First task";
        // The TaskInfo for the task includes the registered wait
        // handle returned by RegisterWaitForSingleObject.  This
        // allows the wait to be terminated when the object has
        // been signaled once (see WaitProc).
        ti.Handle = ThreadPool.RegisterWaitForSingleObject(
            ev,
            new WaitOrTimerCallback(WaitProc),
            ti,
            100,
            false
        );

        // The main thread waits three seconds, to demonstrate the
        // time-outs on the queued thread, and then signals.
        Thread.Sleep(3100);
        Console.WriteLine("Main thread signals.");
        ev.Set();

        // The main thread sleeps, which should give the callback
        // method time to execute.  If you comment out this line, the
        // program usually ends before the ThreadPool thread can execute.
        Thread.Sleep(1000);
        // If you start a thread yourself, you can wait for it to end
        // by calling Thread.Join.  This option is not available with
        // thread pool threads.
    }
  
    // The callback method executes when the registered wait times out,
    // or when the WaitHandle (in this case AutoResetEvent) is signaled.
    // WaitProc unregisters the WaitHandle the first time the event is
    // signaled.
    public static void WaitProc(object state, bool timedOut) {
        // The state object must be cast to the correct type, because the
        // signature of the WaitOrTimerCallback delegate specifies type
        // Object.
        TaskInfo ti = (TaskInfo) state;

        string cause = "TIMED OUT";
        if (!timedOut) {
            cause = "SIGNALED";
            // If the callback method executes because the WaitHandle is
            // signaled, stop future execution of the callback method
            // by unregistering the WaitHandle.
            if (ti.Handle != null)
                ti.Handle.Unregister(null);
        }

        Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.",
            ti.OtherInfo,
            Thread.CurrentThread.GetHashCode().ToString(),
            cause
        );
    }
}

例2:
using System;
using System.Threading;

class State
{
 private int nCalledTimes = 0;
 public void Called()
 {
  Interlocked.Increment(ref nCalledTimes);
 }
 public int CalledTimes
 {
  get
  {
   return nCalledTimes;
  }
 }
}

class App
{
 static public void PeriodicMethod(object state , bool timeOut)
 {
  // timeOut为false时,说明等待有效,否则超时
  Console.WriteLine("/nThread {0}开始处理定时事件",Thread.CurrentThread.GetHashCode());
  if(!timeOut)
   Console.WriteLine("获得等待信号");
  else
   Console.WriteLine("超时事件发生");
  
  if(state!=null)
  {
   ((State)state).Called();
   Console.WriteLine("调用了{0}次",((State)state).CalledTimes);
  }
  Thread.Sleep(100);
  Console.WriteLine("Thread {0}处理定时事件完毕/n",Thread.CurrentThread.GetHashCode());
 }
 
 static public void Main()
 {
  AutoResetEvent myEvent = new AutoResetEvent(false);
  WaitOrTimerCallback waitOrTimerCallback = new WaitOrTimerCallback(App.PeriodicMethod);
  int timeout = 1000;
  bool executeOnlyOnce = false;
  
  State state = new State();
  
  ThreadPool.RegisterWaitForSingleObject(myEvent , waitOrTimerCallback , state ,timeout,executeOnlyOnce);
  //Thread.Sleep(10000);
  myEvent.Set();
  Console.WriteLine("按任意键退出");
  Console.ReadLine();
 }
}

3、System.Threading.Timer
A.实例化一个TimerCallback代理callback
B.创建一个System.Threading.Timer实例timer
C.如果有必要,调用 timer.Change重新设置timer的durTime和period
D.用timer.Dispose释放timer
using System;
using System.Threading;

class State
{
 private int threadID = -1;
 private AutoResetEvent firstTimerFired = null;
 public State(int threadID , AutoResetEvent firstTimerFired)
 {
  this.threadID = threadID;
  this.firstTimerFired = firstTimerFired;
 }
 
 public void Show()
 {
  Console.WriteLine("thread.HashCode={0}/tthreadID={1}在工作",Thread.CurrentThread.GetHashCode(),threadID);
 }
 
 public AutoResetEvent FirstTimerFired
 {
  get
  {
   return firstTimerFired;
  }
  set
  {
   firstTimerFired = value;
  }
 }
}

class App
{
 public static void Main()
 {
  Console.WriteLine("每2秒执行一次时钟事件");
  TimerCallback callback = new TimerCallback(App.CheckStatus);
  Timer timer1 = new Timer(callback , null ,1000 ,2000);
  AutoResetEvent firstTimerFired = new AutoResetEvent(false);
  State state = new State(2,firstTimerFired);
  
  Timer timer2 = new Timer(callback ,state , 5000 ,0);//定时器事件只触发一次,period为0
  firstTimerFired.WaitOne();
  
  Console.WriteLine("按回车继续...");
  Console.ReadLine();
  
  timer2.Change(2000,1000);
  Console.WriteLine("按回车继续...");
  Console.ReadLine();
  
  timer1.Dispose();
  timer2.Dispose();
 }
 
 static void CheckStatus(object state)
 {
  if (state !=null)
  {
   ((State)state).Show();
   if(((State)state).FirstTimerFired != null)
    ((State)state).FirstTimerFired.Set();
  }
  else
  {
   Console.WriteLine("tread.HashCode = {0}/tthreadID={1}在工作",Thread.CurrentThread.GetHashCode(),-1);
  }
 }
}

4、System.Timers.Timer
基于服务器的计时器的关键编程元素
Timer 组件引发一个名为 Timer.Elapsed 的事件。您可以为这个事件创建处理程序来执行处理要发生的一切。

Timer 组件的一些更重要的属性和方法还包含:

Interval 属性用来设置引发事件的时间范围,以毫秒计。例如,值为 1000 的时间间隔将一秒钟引发一次事件。
AutoReset 属性决定在给定时间间隔过去之后计时器是否继续引发事件。如果设置成 true,计时器继续重新计算时间间隔并引发事件。如果为 false,它在时间间隔过去后只引发一次事件,然后停止。
Start 方法将计时器的 Enabled 属性设置为 true,它允许计时器开始引发事件。如果计时器已经是启用状态,则调用 Start 方法将重置该计时器。
Stop 方法将计时器的 Enabled 属性设置成 false,以防止计时器再引发事件。
A.创建System.Timers.Timer对象kicker
B.设置周期
C.设置AutoReset为true
D.设置kicker的Elapsed事件
E.启动kicker
F.如果需要,可以重新设置kicker的Interval属性
G.停止记时器
using System;
using System.Timers;
using System.Threading;

class App
{
 private static DateTime stopTime = new DateTime(2005,4,2);
 static void ElapsedHandler(object sender , ElapsedEventArgs e)
 {
  if (DateTime.Compare(e.SignalTime , stopTime) > 0 )
  {
   Console.WriteLine("Thread {0} 处理定事事件",Thread.CurrentThread.GetHashCode());
   Thread.Sleep(100);
  }
 }
 
 static public void Main()
 {
  System.Timers.Timer kicker = new System.Timers.Timer();
  kicker.Interval =1000;
  kicker.AutoReset = true;
  kicker.Elapsed += new ElapsedEventHandler(ElapsedHandler);
  kicker.Start();
  Thread.Sleep(2100);
  Console.WriteLine("改变时间间隔");
  kicker.Interval = 2000;
  Thread.Sleep(2100);
  Console.WriteLine("结束定事器");
  //kicker.Stop();
  stopTime = DateTime.Now;
  Thread.Sleep(2100);
  Console.WriteLine("重新启动定事器");
  kicker.Start();
  Thread.Sleep(8100);
  Console.WriteLine("按任意键退出");
  //Console.ReadLine();
  //Thread.Sleep(14100);
  kicker.Stop();
  stopTime = DateTime.Now;
 }
}

System.Winforms.Timer、System.Threading.Timer、System.Timers.Timer,通过设置定时周期、定时事件、可以启动、终止、再启动定时器、重新设置定时器属性等。功能依次增强。
ThreadPool一旦设置好时钟属性并启动后,就不能对定时器进行控制。
《.net核心技术-原理与架构》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值