btcpayserver/BTCPayServer.Tests/MockDelay.cs

67 lines
1.8 KiB
C#
Raw Permalink Normal View History

2020-06-29 04:44:35 +02:00
using System;
2019-01-16 11:14:45 +01:00
using System.Collections.Generic;
using System.Globalization;
2020-06-28 10:55:27 +02:00
using System.Linq;
2019-01-16 11:14:45 +01:00
using System.Threading;
using System.Threading.Tasks;
namespace BTCPayServer.Tests
{
public class MockDelay : IDelay
{
class WaitObj
{
public DateTimeOffset Expiration;
public TaskCompletionSource<bool> CTS;
}
readonly List<WaitObj> waits = new List<WaitObj>();
2019-01-16 11:14:45 +01:00
DateTimeOffset _Now = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
public async Task Wait(TimeSpan delay, CancellationToken cancellation)
{
WaitObj w = new WaitObj();
w.Expiration = _Now + delay;
w.CTS = new TaskCompletionSource<bool>();
using (cancellation.Register(() =>
{
w.CTS.TrySetCanceled();
}))
{
lock (waits)
{
waits.Add(w);
}
await w.CTS.Task;
}
}
public async Task Advance(TimeSpan time)
2019-01-16 11:14:45 +01:00
{
_Now += time;
List<WaitObj> overdue = new List<WaitObj>();
2019-01-16 11:14:45 +01:00
lock (waits)
{
foreach (var wait in waits.ToArray())
{
if (_Now >= wait.Expiration)
{
overdue.Add(wait);
2019-01-16 11:14:45 +01:00
waits.Remove(wait);
}
}
}
foreach (var o in overdue)
o.CTS.TrySetResult(true);
try
{
await Task.WhenAll(overdue.Select(o => o.CTS.Task).ToArray());
}
catch { }
2019-01-16 11:14:45 +01:00
}
public override string ToString()
{
return _Now.Millisecond.ToString(CultureInfo.InvariantCulture);
}
}
}