Search code examples
c#system.diagnosticsttl

C# How to implement a Time To Live function to a big list's content


I'm building an app that listens to Wamp protocol messages and stores them in a List<MySpecialClass>. Since the traffic is, quite frankly, wild (About 1-1.5 thousand messages in a minute or two), I would like to implement some way of cleaning this list automatically of terminated entries.

My idea was to provide MySpecialClass with a System.Diagnostics.Stopwatch isTerminated field. Recieving a Wamp message that some entry was terminated would run a isTerminated.StartNew(). And a regular (but much less frequent than 60s) loop through the List<MySpecialClass> would make sure to List.Remove() any MySpecialClass that has isTerminated.ElapsedMilliseconds>60000.

I should note, that due to some complex stuff the terminated entry can then be reinstated again with another Wamp message, which, in accordance to my idea, would call a isTerminated.Reset().

I'd go ahead and do it, but I'm new at this, I'm not sure what kind of trouble I'm getting myself into with the System.Diagnostics.Stopwatch. Would it cut my memory usage or increase it?

I'd love to hear feedback on this method I'm thinking about as well as some suggestions about how one should go about cleaning their lists. Cheers!

EDIT

I guess I'm prone to overthinking problems, sorry for your trouble. A Pikoh's idea in the comments is what I needed.


Solution

  • Turns out I could just add a timestamp field in my class, that would show when the message got terminated and check that, which is marginally better than my idea. Thanks Pikoh.