多线程编程学习笔记(五)[2]

[入库:2006年2月23日] [更新:2007年3月24日]

本文简介:

        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;
  }
 }
}

本文关键:多线程编程学习笔记(五)
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top