首页 > 编程语言 >C#更加精准的时钟

C#更加精准的时钟

时间:2023-03-11 10:46:31浏览次数:29  
标签:C# sysTimer private int void stopwatch public 精准 时钟

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace SKII.SKIITimer
{
    /// <summary>
    /// 相差2,3毫秒
    /// </summary>
    public sealed class MillisecondTimer : IComponent, IDisposable
    {
        private static TimerCaps caps;
        private int interval;
        private bool isRunning;
        private int resolution;
        private TimerCallback timerCallback;
        private int timerID;

        public int Interval
        {
            get
            {
                return this.interval;
            }
            set
            {
                if ((value < caps.periodMin) || (value > caps.periodMax))
                {
                    throw new Exception("超出计时范围!");
                }
                this.interval = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public bool IsRunning
        {
            get
            {
                return this.isRunning;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public ISite Site
        {
            set;
            get;
        }

        public event EventHandler Disposed;  // 这个事件实现了IComponet接口
        public event EventHandler Tick;

        static MillisecondTimer()
        {
            timeGetDevCaps(ref caps, Marshal.SizeOf(caps));
        }

        public MillisecondTimer()
        {
            this.interval = caps.periodMin;    // 
            this.resolution = caps.periodMin;  //

            this.isRunning = false;
            this.timerCallback = new TimerCallback(this.TimerEventCallback);

        }

        public MillisecondTimer(IContainer container)
            : this()
        {
            container.Add(this);
        }

        ~MillisecondTimer()
        {
            timeKillEvent(this.timerID);
        }

        public void Start()
        {
            if (!this.isRunning)
            {
                this.timerID = timeSetEvent(this.interval, this.resolution, this.timerCallback, 0, 1); // 间隔性地运行

                if (this.timerID == 0)
                {
                    throw new Exception("无法启动计时器");
                }
                this.isRunning = true;
            }
        }

        public void Stop()
        {
            if (this.isRunning)
            {
                timeKillEvent(this.timerID);
                this.isRunning = false;
            }
        }

        /// <summary>
        /// 实现IDisposable接口
        /// </summary>
        public void Dispose()
        {
            timeKillEvent(this.timerID);
            GC.SuppressFinalize(this);
            EventHandler disposed = this.Disposed;
            if (disposed != null)
            {
                disposed(this, EventArgs.Empty);
            }
        }

        //***************************************************  内部函数  ******************************************************************
        [DllImport("winmm.dll")]
        private static extern int timeSetEvent(int delay, int resolution, TimerCallback callback, int user, int mode);


        [DllImport("winmm.dll")]
        private static extern int timeKillEvent(int id);


        [DllImport("winmm.dll")]
        private static extern int timeGetDevCaps(ref TimerCaps caps, int sizeOfTimerCaps);
        //  The timeGetDevCaps function queries the timer device to determine its resolution. 



        private void TimerEventCallback(int id, int msg, int user, int param1, int param2)
        {
            if (this.Tick != null)
            {
                this.Tick(this, null);  // 引发事件
            }
        }

        //***************************************************  内部类型  ******************************************************************

        private delegate void TimerCallback(int id, int msg, int user, int param1, int param2); // timeSetEvent所对应的回调函数的签名


        /// <summary>
        /// 定时器的分辨率(resolution)。单位是ms,毫秒
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        private struct TimerCaps
        {
            public int periodMin;
            public int periodMax;
        }
    }
}
        private void sysTimer_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < 1000; i++)
            {

            }
            //需要定时执行的内容
            this.Invoke((EventHandler)delegate
            {
                txtShow.Text += "时间:" + stopwatch.ElapsedMilliseconds.ToString() + "\r\n";

            });

        }

        private void btnSKIITimer_Click(object sender, EventArgs e)
        {
            stopwatch.Start();
            txtShow.Text += "时间1:" + stopwatch.ElapsedMilliseconds.ToString() + "\r\n";
            delay(1000);
            txtShow.Text += "时间2:" + stopwatch.ElapsedMilliseconds.ToString() + "\r\n";
            delay(1000);
            txtShow.Text += "时间3:" + stopwatch.ElapsedMilliseconds.ToString() + "\r\n";
            delay(1000);
            txtShow.Text += "时间4:" + stopwatch.ElapsedMilliseconds.ToString() + "\r\n";
            delay(1000);
            txtShow.Text += "时间5:" + stopwatch.ElapsedMilliseconds.ToString() + "\r\n";
            stopwatch.Stop();

            if (sysTimer.IsRunning)
            {
                sysTimer.Stop();
                stopwatch.Stop();
                btnSKIITimer.Text = "开始";
            }
            else
            {
                sysTimer.Start();
                stopwatch.Start();
                btnSKIITimer.Text = "停止";
            }
        }

        //调用API函数
        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceCounter(ref long x);
        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceFrequency(ref long x);
        //定义延迟函数
        /// <summary>
        /// 
        /// </summary>
        /// <param name="delay_Time"></param>
        public void delay(long delay_Time)
        {

            long stop_Value = 0;
            long start_Value = 0;
            long freq = 0;
            long n = 0;

            QueryPerformanceFrequency(ref freq);  //获取CPU频率
            long count = delay_Time * freq / 1000;
            QueryPerformanceCounter(ref start_Value); //获取初始前值

            while (n < count) //不能精确判定
            {
                QueryPerformanceCounter(ref stop_Value);//获取终止变量值
                n = stop_Value - start_Value;
            }
        }

//定义
        private MillisecondTimer sysTimer;
        Stopwatch stopwatch = new Stopwatch();
//初始化
            sysTimer = new MillisecondTimer();
            sysTimer.Tick += sysTimer_Tick;
            sysTimer.Interval = 100; //每秒执行

 

标签:C#,sysTimer,private,int,void,stopwatch,public,精准,时钟
From: https://www.cnblogs.com/kingkie/p/17205422.html

相关文章

  • docker——Error response from daemon: manifest for java:8 not found
    华为linux版本用docker拉取java8报错一开始以为网络问题。但是pingwww.baidu.com没问题。百度查看华为解析  更换安装命令dockerpullopenjdk:8      ......
  • C#实现右下角托盘程序,默认不显示窗体,关闭窗体时隐藏而不退出
    Windows右下角托盘程序是Windows系统的一大特色。在某些场景非常适用。C#中提供了notifyIcon组件实现托盘程序。因业务需要实现一个假后台程序,开机自动启动且默认不显示窗......
  • token解决cookie的弊端
    token解决cookie的弊端目录token解决cookie的弊端cookie的弊端token解决弊端一什么是token和JWTJWT的构成token工作流程token解决弊端二CSRF攻击token防止CSRFcookie的弊......
  • 使用Go语言创建WebSocket服务器和客户端
    WebSocket是一种新型的网络通信协议,可以在Web应用程序中实现双向通信。在这篇文章中,我们将介绍如何使用Go语言编写一个简单的WebSocket服务器。首先,我们需要使用G......
  • C. Errich-Tac-Toe 构造
    C1.Errich-Tac-Toe(EasyVersion)(构造)https://codeforces.com/contest/1450/problem/C1题意:给定n*n矩阵,最初全为空,在其中可以放置X和O,若相同的连成一行或一列则获胜,每......
  • vue中执行异步函数async和await的用法
    在开发中,可能会遇到两个或多个函数异步执行的情况,对于Vue中函数的异步函数执行做了一个小总结,如下:异步执行使用async和await完成created(){this.init()},meth......
  • LeetCode|2457. 美丽整数的最小增量
    题目链接:2457.美丽整数的最小增量给你两个正整数n和target。如果某个整数每一位上的数字相加小于或等于target,则认为这个整数是一个美丽整数。找出并返回满......
  • Docker安装
    背景最近接手了几个项目,发现项目的部署基本上都是基于Docker的,幸亏在几年前已经熟悉的Docker的基本使用,没有抓瞎。这两年随着云原生的发展,Docker在云原生中的作用使得它也......
  • JavaScript表单
          ......
  • can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the t
     如何解决这个问题:TypeError:can'tconvertcuda:0devicetypetensortonumpy.UseTensor.cpu()tocopythetensortohostmemoryfirst.这个错误通常出现在试......