using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Security;
namespace demo.ClassHelper.TimeOperate
{
class TimerHelper
{
///
/// 获取时间的精度
///
///
///
[SuppressUnmanagedCodeSecurity]
[DllImport("kernel32")]
private static extern bool QueryPerformanceFrequency(ref long PerformanceFrequency);
///
/// 获取时间计数
///
///
///
[SuppressUnmanagedCodeSecurity]
[DllImport("kernel32")]
private static extern bool QueryPerformanceCounter(ref long PerformanceCount);
[DllImport("kernel32")]
static extern IntPtr GetCurrentThread();
[DllImport("kernel32")]
static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);
[DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
private long ticksPerSecond = 0;
private long Time = 0;
private long baseTime = 0;
private IntPtr handle;
private bool disposed = false;
///
/// 获取毫秒数
///
private long duration;
public long Duration
{
get
{
QueryPerformanceCounter(ref Time);
return duration = (long)(((double)(Time - baseTime) / (double)ticksPerSecond) * 1000);
}
private set
{
duration = value;
}
}
///
///
///
public TimerHelper()
{
if (QueryPerformanceFrequency(ref ticksPerSecond) == false)
{
// 不支持高性能计数器
throw new ApplicationException("Timer: Performance Frequency Unavailable");
}
Reset();
}
///
/// 复位
///
public void Reset()
{
long time = 0;
IntPtr threadId = GetCurrentThread();
IntPtr previous = SetThreadAffinityMask(threadId, new IntPtr(1));
QueryPerformanceCounter(ref time);
SetThreadAffinityMask(threadId, previous);
baseTime = time;
Time = 0;
}
// 开始计时器
public void Start()
{
// 来让等待线程工作
IntPtr threadId = GetCurrentThread();
IntPtr previous = SetThreadAffinityMask(threadId, new IntPtr(1));
SetThreadAffinityMask(threadId, previous);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
CloseHandle(handle);
handle = IntPtr.Zero;
}
disposed = true;
}
~TimerHelper()
{
Dispose(false);
}
// 返回计时器经过时间(单位:秒)
}
}