You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
3.4 KiB
C#

1 month ago
// ***********************************************************************
// Assembly : Construction
// Author : flythink
// Created : 06-05-2020
//
// Last Modified By : flythink
// Last Modified On : 09-01-2020
// ***********************************************************************
// <copyright file="SlowDownTimer.cs" company="jindongfang">
// Copyright (c) jindongfang. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
namespace Fk.Utils
{
using System;
using System.Threading;
using Timer = System.Timers.Timer;
/// <summary>
/// Delegate SlowDownAction
/// </summary>
public delegate void SlowDownAction();
/// <summary>
/// Class SlowDownTimer.
/// </summary>
public class SlowDownTimer : IDisposable
{
private SlowDownAction action;
private Timer onceTimer;
private SynchronizationContext synchronizationContext;
private bool disposed = false;
/// <summary>
/// Initializes a new instance of the <see cref="SlowDownTimer" /> class.
/// </summary>
/// <param name="interval">The interval.</param>
/// <param name="autoReset">是否重复执行</param>
public SlowDownTimer(double interval, bool autoReset = false)
{
this.synchronizationContext = SynchronizationContext.Current;
this.onceTimer = new Timer(interval);
this.onceTimer.AutoReset = autoReset;
this.onceTimer.Elapsed += this.OnceTimer_Elapsed;
}
/// <summary>
/// Finalizes an instance of the <see cref="SlowDownTimer"/> class.
/// </summary>
~SlowDownTimer()
{
this.Dispose(false);
}
/// <inheritdoc/>
public void Dispose()
{
if (!this.disposed)
{
this.Dispose(true);
}
GC.SuppressFinalize(this);
}
/// <summary>
/// 释放非托管数据
/// </summary>
/// <param name="disposing">是否非托管</param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (this.onceTimer != null)
{
this.onceTimer.Elapsed -= this.OnceTimer_Elapsed;
this.onceTimer.Close();
this.onceTimer.Dispose();
}
// Violates rule: DisposableFieldsShouldBeDisposed.
// Should call aFieldOfADisposableType.Dispose();
this.disposed = true;
// Suppress finalization of this disposed instance.
if (disposing)
{
GC.SuppressFinalize(this);
}
}
}
/// <summary>
/// Invokes the specified action.
/// </summary>
/// <param name="action">The action.</param>
public void Invoke(SlowDownAction action)
{
this.onceTimer.Stop();
this.action = action;
this.onceTimer.Start();
}
private void OnceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.synchronizationContext.Post(_ => { this.action?.Invoke(); }, null);
}
}
}