|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Collections.Concurrent; |
| 4 | +using System.Linq; |
| 5 | +using System.Text; |
| 6 | +using System.Threading.Tasks; |
| 7 | + |
| 8 | +namespace SmartStore.Core.Utilities |
| 9 | +{ |
| 10 | + public static class Throttle |
| 11 | + { |
| 12 | + private readonly static ConcurrentDictionary<string, CheckEntry> _checks = new ConcurrentDictionary<string, CheckEntry>(StringComparer.OrdinalIgnoreCase); |
| 13 | + |
| 14 | + /// <summary> |
| 15 | + /// Performs a throttled check. |
| 16 | + /// </summary> |
| 17 | + /// <param name="key">Identifier for the check process</param> |
| 18 | + /// <param name="interval">Interval between actual checks</param> |
| 19 | + /// <param name="check">The check factory</param> |
| 20 | + /// <returns>Check result</returns> |
| 21 | + public static bool Check(string key, TimeSpan interval, Func<bool> check) |
| 22 | + { |
| 23 | + return Check(key, interval, false, check); |
| 24 | + } |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Performs a throttled check. |
| 28 | + /// </summary> |
| 29 | + /// <param name="key">Identifier for the check process</param> |
| 30 | + /// <param name="interval">Interval between actual checks</param> |
| 31 | + /// <param name="recheckWhenFalse"></param> |
| 32 | + /// <param name="check">The check factory</param> |
| 33 | + /// <returns>Check result</returns> |
| 34 | + public static bool Check(string key, TimeSpan interval, bool recheckWhenFalse, Func<bool> check) |
| 35 | + { |
| 36 | + Guard.NotEmpty(key, nameof(key)); |
| 37 | + Guard.NotNull(check, nameof(check)); |
| 38 | + |
| 39 | + bool added = false; |
| 40 | + var now = DateTime.UtcNow; |
| 41 | + |
| 42 | + var entry = _checks.GetOrAdd(key, x => |
| 43 | + { |
| 44 | + added = true; |
| 45 | + return new CheckEntry { Value = check(), NextCheckUtc = (now + interval) }; |
| 46 | + }); |
| 47 | + |
| 48 | + if (added) |
| 49 | + { |
| 50 | + return entry.Value; |
| 51 | + } |
| 52 | + |
| 53 | + var ok = entry.Value; |
| 54 | + var isOverdue = (!ok && recheckWhenFalse) || (now > entry.NextCheckUtc); |
| 55 | + |
| 56 | + if (isOverdue) |
| 57 | + { |
| 58 | + // Check is overdue: recheck |
| 59 | + ok = check(); |
| 60 | + _checks.TryUpdate(key, new CheckEntry { Value = ok, NextCheckUtc = (now + interval) }, entry); |
| 61 | + } |
| 62 | + |
| 63 | + return ok; |
| 64 | + } |
| 65 | + |
| 66 | + class CheckEntry |
| 67 | + { |
| 68 | + public bool Value { get; set; } |
| 69 | + public DateTime NextCheckUtc { get; set; } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments