You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

124 lines
3.3 KiB
C#

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
{
/// <summary>
/// 获取时间的精度
/// </summary>
/// <param name="PerformanceFrequency"></param>
/// <returns></returns>
[SuppressUnmanagedCodeSecurity]
[DllImport("kernel32")]
private static extern bool QueryPerformanceFrequency(ref long PerformanceFrequency);
/// <summary>
/// 获取时间计数
/// </summary>
/// <param name="PerformanceCount"></param>
/// <returns></returns>
[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;
/// <summary>
/// 获取毫秒数
/// </summary>
private long duration;
public long Duration
{
get
{
QueryPerformanceCounter(ref Time);
return duration = (long)(((double)(Time - baseTime) / (double)ticksPerSecond) * 1000);
}
private set
{
duration = value;
}
}
/// <summary>
///
/// </summary>
public TimerHelper()
{
if (QueryPerformanceFrequency(ref ticksPerSecond) == false)
{
// 不支持高性能计数器
throw new ApplicationException("Timer: Performance Frequency Unavailable");
}
Reset();
}
/// <summary>
/// 复位
/// </summary>
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);
}
// 返回计时器经过时间(单位:秒)
}
}