You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
1.1 KiB
44 lines
1.1 KiB
1 year ago
|
using System.Diagnostics;
|
||
1 year ago
|
|
||
1 year ago
|
namespace StabilityMatrix.Core.Helper;
|
||
1 year ago
|
|
||
|
/// <summary>
|
||
|
/// Enforces a minimum delay if the function returns too quickly.
|
||
|
/// Waits during async Dispose.
|
||
|
/// </summary>
|
||
|
public class MinimumDelay : IAsyncDisposable
|
||
|
{
|
||
|
private readonly Stopwatch stopwatch = new();
|
||
|
private readonly TimeSpan delay;
|
||
|
|
||
|
/// <summary>
|
||
|
/// Minimum random delay in milliseconds.
|
||
|
/// </summary>
|
||
|
public MinimumDelay(int randMin, int randMax)
|
||
|
{
|
||
|
stopwatch.Start();
|
||
|
Random rand = new();
|
||
|
delay = TimeSpan.FromMilliseconds(rand.Next(randMin, randMax));
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// Minimum fixed delay in milliseconds.
|
||
|
/// </summary>
|
||
|
public MinimumDelay(int delayMilliseconds)
|
||
|
{
|
||
|
stopwatch.Start();
|
||
|
delay = TimeSpan.FromMilliseconds(delayMilliseconds);
|
||
|
}
|
||
|
|
||
|
public async ValueTask DisposeAsync()
|
||
|
{
|
||
|
stopwatch.Stop();
|
||
|
var elapsed = stopwatch.Elapsed;
|
||
|
if (elapsed < delay)
|
||
|
{
|
||
|
await Task.Delay(delay - elapsed);
|
||
|
}
|
||
|
GC.SuppressFinalize(this);
|
||
|
}
|
||
|
}
|