public async Task <List <E> > ListenAsync <E>(object listenId, Func <IQueryable <E>, IQueryable <E> > filter, TimeSpan maxWait, CancellationToken token) where E : EntityBase { logger.LogTrace($"ListenNewAsync called for maxWait {maxWait}"); using (CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(token)) { //We MUST start listening FIRST so we DON'T miss anything AT ALL (we could miss valuable signals that occur while reading initially) var listener = signaler.ListenAsync(listenId, q => filter(q.Where(e => e is E).Cast <E>()), maxWait, linkedCts.Token); DateTime start = DateTime.Now; //Putting this down here to minimize startup time before listen (not that this little variable really matters) var baseE = await query.GetQueryableAsync <E>(); var results = await LockAsync(() => query.GetListAsync(filter(baseE.Select(x => (E)x)))); if (results.Count > 0) { linkedCts.Cancel(); try { //Yes, we are so confident that we don't even worry about waiting properly await listener; } catch (OperationCanceledException) {} //This is expected return(results); } else { return((await listener).Cast <E>().ToList()); } } }