W
whtinkm
Hi, All
Recently, my project need some code like following:
using System;
using System.Threading;
namespace MyTimerTest
{
class Class1
{
protected System.Threading.Timer guarder;
private string testFlag="";
public void Init()
{
System.Console.WriteLine("Begin Test.....");
guarder=new Timer(new
TimerCallback(CheckCurrentState),null,5000,100);
}
public void Destroy()
{
//Dispose timer
}
protected void CheckCurrentState(object state)
{
string
strTemp=System.Threading.Thread.CurrentThread.GetHashCode().ToString();
try
{
if(testFlag!="" && testFlag!=strTemp)
{
System.Console.WriteLine("Fatal error1: "+testFlag+","+strTemp);
}
testFlag=strTemp;
guarder.Change(Timeout.Infinite,0); //disable the timer
System.Threading.Thread.Sleep(300);
}
catch(Exception ex)
{
System.Console.WriteLine("CheckCurrentState: "+ex.Message);
}
finally
{
if(testFlag!=strTemp)
{
System.Console.WriteLine("Fatal error2: "+testFlag+","+strTemp);
}
testFlag="";
guarder.Change(100,100); //enable timer again
}
}
[STAThread]
static void Main(string[] args)
{
Class1 dd=new Class1();
dd.Init();
System.Console.ReadLine();
dd.Destroy();
}
}
}
I confused that when I run the simple test code for a moment, i will
get the following output
Fatal error1: 1,2
Fatal error2 ,2
......
I think when it enters the event process it has disable the timer using
Change(Timeout.Infinite,0)
According to the output, the timer fires multi-times, why?
Thanks for any ideas
Harry
Recently, my project need some code like following:
using System;
using System.Threading;
namespace MyTimerTest
{
class Class1
{
protected System.Threading.Timer guarder;
private string testFlag="";
public void Init()
{
System.Console.WriteLine("Begin Test.....");
guarder=new Timer(new
TimerCallback(CheckCurrentState),null,5000,100);
}
public void Destroy()
{
//Dispose timer
}
protected void CheckCurrentState(object state)
{
string
strTemp=System.Threading.Thread.CurrentThread.GetHashCode().ToString();
try
{
if(testFlag!="" && testFlag!=strTemp)
{
System.Console.WriteLine("Fatal error1: "+testFlag+","+strTemp);
}
testFlag=strTemp;
guarder.Change(Timeout.Infinite,0); //disable the timer
System.Threading.Thread.Sleep(300);
}
catch(Exception ex)
{
System.Console.WriteLine("CheckCurrentState: "+ex.Message);
}
finally
{
if(testFlag!=strTemp)
{
System.Console.WriteLine("Fatal error2: "+testFlag+","+strTemp);
}
testFlag="";
guarder.Change(100,100); //enable timer again
}
}
[STAThread]
static void Main(string[] args)
{
Class1 dd=new Class1();
dd.Init();
System.Console.ReadLine();
dd.Destroy();
}
}
}
I confused that when I run the simple test code for a moment, i will
get the following output
Fatal error1: 1,2
Fatal error2 ,2
......
I think when it enters the event process it has disable the timer using
Change(Timeout.Infinite,0)
According to the output, the timer fires multi-times, why?
Thanks for any ideas
Harry