User Tools

Site Tools

blog:2023-04-18_c_supertimer_20ms_count_implement



2023-04-18 C#: SuperTimer 20mS Count Implement

  • I have implement a SuperTimer class but it seems if I did not dispose it, it will accumate in memory event the object exit the suage function.
  • So, I rewrite it with dispose() implement as follows.

Code

  •     public class SuperTimer : IDisposable
        {
            public System.Timers.Timer gTickTimer = new System.Timers.Timer(20);
            private UInt32 gTickCount;
            private UInt32 aStartTick;
            private UInt32 aDuration;
            private UInt32 aStopTick;
            // Constructor
            public SuperTimer()
            {
                gTickCount = 0;
                // Have the timer fire repeated events (true is the default)
                gTickTimer.AutoReset = true;
                // Hook up the Elapsed event for the timer. 
                gTickTimer.Elapsed += gTickTimer_Elapsed;
                // Start the timer
                gTickTimer.Enabled = true;
            }
            private void gTickTimer_Elapsed(Object source, System.Timers.ElapsedEventArgs e)
            {
                gTickCount += 1;
            }
            public void StartTimer(UInt32 inDurationMS)
            {
                aStartTick = gTickCount;
                aDuration = inDurationMS / 20; // 每20mS回Call一次
                aStopTick = aStartTick + aDuration;
            }
    
            public bool TimerExpired()
            {
                if ((aStopTick == 0) || (gTickCount >= aStopTick))
                {
                    aStopTick = 0;
                    return (true);
                }
                else
                    return (false);
            }
    
            bool disposed;
            protected virtual void Dispose(bool disposing)
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        //dispose managed resources
                    }
                }
                //dispose unmanaged resources
                disposed = true;
            }
            public void Dispose()
            {
                gTickTimer.Stop();
                gTickTimer.Dispose();
                Dispose(true);
                GC.SuppressFinalize(this);
            }
        }

TAGS

  • 100 person(s) visited this page until now.

Permalink blog/2023-04-18_c_supertimer_20ms_count_implement.txt · Last modified: 2023/04/18 17:47 by jethro

oeffentlich