fchen

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
设计一个每隔20ms检查一次状态的程序,用System.Timers.Timer做测试时发现,前几次执行timer调用函数的时间相同(把间隔改到1s以上时无此问题),用lock也用(可能是我不太会用lock)。
改为System.Threading.Timer测试发现:
Threading和Timers的timer在小间隔时都存在此问题,分析后初步判断是初次运行前的间隔时间的问题。
Timers的无法设置初次启动前间隔所以设置20ms间隔时第一次进入前的间隔也是20ms
Threading的可以设置初次启动前的间隔,设置较大间隔后启动,便没有了初次运行时多线程同时进入的情况。

timerClose = new System.Threading.Timer(new TimerCallback(timerCall), null , 20, 20);//多次进入
timerClose = new System.Threading.Timer(new TimerCallback(timerCall), null , 1000, 20);//正常进入



测试用的代码:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Timers;
using System.Threading;

namespace WindowsApplication3
{
    
static class Program
    
{
        
/// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>

        [STAThread]
        
static void Main()
        
{
            
//System.Threading.Timer thrTimer = new System.Threading.Timer();

            
            

            System.Timers.Timer timer 
= new System.Timers.Timer();
            timer.Elapsed 
+= new ElapsedEventHandler(timer_Elapsed);

            timer.AutoReset 
= true;
            timer.Interval 
=20;

            System.Threading.Timer timerClose;
            
//解决初次进入timer调用函数时多线程同时访问函数的问题
            
//Threading和Timers的timer都存在此问题分析后初步判断是初次运行前的间隔时间的问题
            
//Timers的无法设置初次启动前间隔所以设置20ms间隔时第一次进入前的间隔也是20ms
            
//Threading的可以设置初次启动前的间隔,设置较大间隔后启动,便没有了初次运行时多线程同时进入的情况。
            
//timerClose = new System.Threading.Timer(new TimerCallback(timerCall), null , 1000, 20);
            
//timerClose = new System.Threading.Timer(new TimerCallback(timerCall), null , 20, 20);
            
//timer.Start();


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(
false);
            Application.Run(
new Form1());
        }

        
public static  void timer_Elapsed(object sender, ElapsedEventArgs e)
        
{
            Console.Out.WriteLine(
"system   :"+DateTime.Now + " " + DateTime.Now.Millisecond + " "+DateTime .Now.TimeOfDay.TotalMilliseconds );

        }

        
//object oo = new object();
        
//static int inTimer = 0; 
        public static void timerCall(object obj)
        
{

            
//timerClose.Dispose();
            
//lock (this)
            
//if (Interlocked.Exchange(ref inTimer, 1) == 0) 
            {
                
//Console.Out.WriteLine(Environment.TickCount);
                Console.Out.WriteLine("Threading:" + DateTime.Now + " " + DateTime.Now.Millisecond + " " + DateTime.Now.TimeOfDay.TotalMilliseconds);
                
//this.Close();
                
//Interlocked.Exchange(ref inTimer, 0); 
            }


        }





    }

}

posted on 2008-05-09 11:08  wills  阅读(5856)  评论(0编辑  收藏  举报