C# 毫秒级计时线程

引用DLL

        [DllImport("winmm")]
        static extern uint timeGetTime();

        [DllImport("winmm")]
        static extern void timeBeginPeriod(int t);

        [DllImport("winmm")]
        static extern uint timeEndPeriod(int t);

声明变量实例化

        Thread timerthread;
        private void Form1_Load(object sender, EventArgs e)
        {
            timerthread = new Thread(timer);
        }

实现方式

        private void timer()
        {
            uint timerstart = timeGetTime();
            while (true)
            {
                uint i = 0;
                while (i < 1)//时间间隔(ms)
                {
                    i = timeGetTime() - timerstart;
                }
                timerstart = timeGetTime();
                timerfunction();//需要循环运行的函数;           
            }
        }
        private void timerfunction()
        {
            //需要执行的业务
        }
        int i = 0;
        private void button2_Click(object sender, EventArgs e)
        {
            timeBeginPeriod(1);

            timerthread.Start();//计时器线程启动
        }
        private void button3_Click(object sender, EventArgs e)
        {
            timerthread.Abort();//计时器线程终止

            timeEndPeriod(1);
        }

 

posted @ 2022-08-01 13:01  芈璐  阅读(364)  评论(0编辑  收藏  举报