Non-reentrant timers

后端 未结 5 483
别那么骄傲
别那么骄傲 2020-12-11 04:30

I have a function that I want to invoke every x seconds, but I want it to be thread-safe.

Can I set up this behavior when I am creating the timer? (I don\'t

5条回答
  •  我在风中等你
    2020-12-11 05:03

    using System;
    using System.Diagnostics;
    
    /// 
    ///     Updated the code.
    /// 
    public class NicerFormTimer : IDisposable {
    
        public void Dispose() {
            using ( this.Timer ) { }
    
            GC.SuppressFinalize( this );
        }
    
        private System.Windows.Forms.Timer Timer { get; }
    
        /// 
        ///     Perform an  after the given interval (in ).
        /// 
        /// 
        /// Perform the  again. (Restarts the .)
        /// 
        public NicerFormTimer( Action action, Boolean repeat, Int32? milliseconds = null ) {
            if ( action == null ) {
                return;
            }
    
            this.Timer = new System.Windows.Forms.Timer {
                Interval = milliseconds.GetValueOrDefault( 1000 )
            };
    
            this.Timer.Tick += ( sender, args ) => {
                try {
                    this.Timer.Stop();
                    action();
                }
                catch ( Exception exception ) {
                    Debug.WriteLine( exception );
                }
                finally {
                    if ( repeat ) {
                        this.Timer.Start();
                    }
                }
            };
    
            this.Timer.Start();
        }
    
    }
    
    /// 
    ///     Updated the code.
    /// 
    public class NicerSystemTimer : IDisposable {
    
        public void Dispose() {
            using ( this.Timer ) { }
    
            GC.SuppressFinalize( this );
        }
    
        private System.Timers.Timer Timer { get; }
    
        /// 
        ///     Perform an  after the given interval (in ).
        /// 
        /// 
        /// Perform the  again. (Restarts the .)
        /// 
        public NicerSystemTimer( Action action, Boolean repeat, Double? milliseconds = null ) {
            if ( action == null ) {
                return;
            }
    
            this.Timer = new System.Timers.Timer {
                AutoReset = false,
                Interval = milliseconds.GetValueOrDefault( 1000 )
            };
    
            this.Timer.Elapsed += ( sender, args ) => {
                try {
                    this.Timer.Stop();
                    action();
                }
                catch ( Exception exception ) {
                    Debug.WriteLine( exception );
                }
                finally {
                    if ( repeat ) {
                        this.Timer.Start();
                    }
                }
            };
    
            this.Timer.Start();
        }
    
    }
    

提交回复
热议问题