class ManualTimer //自定义计时器
{
public delegate void ManualTimerEventHandler(object sender);
public event ManualTimerEventHandler Tick;
private uint currentTime, nextTickTime, tickTime;
private int interval;
public int Interval
{
get { return interval; }
set
{
interval = value;
tickTime = (uint)interval;
}
}
private bool running = false;
private Thread thread;
public bool isRun
{
get { return running; }
}
[DllImport("kernel32")]
private static extern uint GetTickCount();
[DllImport("winmm")]
static extern uint timeGetTime();
[DllImport("winmm")]
static extern void timeBeginPeriod(int t);
[DllImport("winmm")]
static extern void timeEndPeriod(int t);
public ManualTimer()
{
}
private void Run1()//GetTickCount()
{
currentTime = GetTickCount();
nextTickTime = currentTime + tickTime;
while (running)
{
while (currentTime < nextTickTime)
{
Thread.Sleep(1);
currentTime = GetTickCount();
}
nextTickTime = currentTime + tickTime;
if (Tick != null)
{
Tick(this);
}
}
}
private void Run()//timeGetTime()
{
timeBeginPeriod(1);
currentTime = timeGetTime();
nextTickTime = currentTime + tickTime;
while (running)
{
while (currentTime < nextTickTime)
{
Thread.Sleep(1);
currentTime = timeGetTime();
timeEndPeriod(1);
}
nextTickTime = currentTime + tickTime;
if (Tick != null)
{
Tick(this);
}
}
}
public void Start()
{
running = true;
thread = new Thread(Run);
thread.Priority = ThreadPriority.Highest;
thread.Start();
}
public void Stop()
{
running = false;
thread.Abort();
}
~ManualTimer()
{
// running = false;
// timerThread.Abort();
if (running)
{
Stop();
}
}
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...