From d9bccb9c199e3e83d4de77fb40c3c8227fe753d0 Mon Sep 17 00:00:00 2001 From: MihaZupan Date: Sat, 8 May 2021 03:01:08 +0200 Subject: [PATCH] Use more reliable WaitForEventCountersAsync in caching test --- .../System.Runtime.Caching/CountersTest.cs | 31 +++++++++++++++++-- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/libraries/System.Runtime.Caching/tests/System.Runtime.Caching/CountersTest.cs b/src/libraries/System.Runtime.Caching/tests/System.Runtime.Caching/CountersTest.cs index 0b7f0db2cbda52..16f363b67750b8 100644 --- a/src/libraries/System.Runtime.Caching/tests/System.Runtime.Caching/CountersTest.cs +++ b/src/libraries/System.Runtime.Caching/tests/System.Runtime.Caching/CountersTest.cs @@ -77,9 +77,10 @@ private async Task PollCounters(string cacheName) var events = new ConcurrentQueue(); using (var listener = new TestEventListener("System.Runtime.Caching." + cacheName, EventLevel.Verbose, eventCounterInterval: 0.1d)) { - // Yup. This Task.Delay() is ugly. There actually isn't a way to simply 'poll' the - // 'polling' counters. This is how System.Net.Http tests their polling counters too. - await listener.RunWithCallbackAsync(events.Enqueue, async () => await Task.Delay(200)); + await listener.RunWithCallbackAsync(events.Enqueue, async () => + { + await WaitForEventCountersAsync(events); + }); } Dictionary eventCounters = events @@ -133,5 +134,29 @@ private async Task PollCounters(string cacheName) return counters; } + + private static async Task WaitForEventCountersAsync(ConcurrentQueue events) + { + DateTime startTime = DateTime.UtcNow; + int startCount = events.Count; + + while (events.Skip(startCount).Count(e => IsTurnoverEventCounter(e)) < 2) + { + if (DateTime.UtcNow.Subtract(startTime) > TimeSpan.FromSeconds(30)) + throw new TimeoutException($"Timed out waiting for EventCounters"); + + await Task.Delay(100); + } + + static bool IsTurnoverEventCounter(EventWrittenEventArgs e) + { + if (e.EventName != "EventCounters") + return false; + + var dictionary = (IDictionary)e.Payload.Single(); + + return (string)dictionary["Name"] == "turnover"; + } + } } }