Environment.TickCount is not enough

后端 未结 6 1080
别那么骄傲
别那么骄傲 2021-01-13 11:50

I want to know on when was the last time the system was started.

Environment.TickCount will work but it is breaking after 48-49 days because of the limitation of int

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-13 12:18

    I am not a fan of using GetTickCount() for timestamp because it can return negative numbers. Even though using Abs() can help, but it's awkward and not an optimal solution.

    It's better to use Stopwatch in .Net or QueryPerformanceCounter in C++ as timestamp.

    Within a C# application, I create a global Stopwatch object, start it. Later on in the application, I use the Stopwatch.ElapsedMiliseconds as timestamp.

    using System;
    using System.Diagnostics;
    using System.Windows.Forms;
    
    namespace MiscApp
    {
        public partial class Form1 : Form
        {
            private Stopwatch globalTimer = new Stopwatch();
            private long myStamp1 = 0;
            public Form1()
            {
                InitializeComponent();
                globalTimer.Start();
            }
    
            private void SomeFunction()
            {
                if (globalTimer.ElapsedMilliseconds - myStamp1 >= 3000)
                {
                    myStamp1 = globalTimer.ElapsedMilliseconds;
                    //Do something here...
                }
            }
        }
    }
    

提交回复
热议问题