protected override async Task RunAsync(CancellationToken cancellationToken) { TimeSpan timeSpan = new TimeSpan(0, 0, 30); ServiceEventSource.Current.ServiceMessage( this, "Partition {0} started processing messages.", this.ServicePartition.PartitionInfo.Id); IReliableDictionary <DateTime, Message> messagesDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <DateTime, Message> >("messages"); //Use this method to periodically clean up messages in the messagesDictionary while (!cancellationToken.IsCancellationRequested) { try { // Remove all the messages that are older than 30 seconds keeping the last 3 messages IEnumerable <KeyValuePair <DateTime, Message> > oldMessages = from t in messagesDictionary where t.Key < (DateTime.Now - timeSpan) orderby t.Key ascending select t; using (ITransaction tx = this.StateManager.CreateTransaction()) { foreach (KeyValuePair <DateTime, Message> item in oldMessages.Take(messagesDictionary.Count() - MessagesToKeep)) { await messagesDictionary.TryRemoveAsync(tx, item.Key); } await tx.CommitAsync(); } } catch (Exception e) { if (!this.HandleException(e)) { ServiceEventSource.Current.ServiceMessage( this, "Partition {0} stopped processing because of error {1}", this.ServicePartition.PartitionInfo.Id, e); break; } } await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken); } }