I need to remove items from list few seconds after i added them. I have now an ObservableCollection to which I add some messages. I need them to be deleted let’s say 5 seconds after they were added. I tried to create a function responsible for adding the items and setting a timer:
public void AddInfoItem(string info)
{
infoList.Add(info);
Timer newTimer = new Timer(5000);
newTimer.Elapsed += new ElapsedEventHandler(this.TimerFunction);
newTimer.Enabled = true;
newTimer.Start();
}
public void TimerFunction(Object sender, EventArgs e)
{
infoList.Clear();
}
I didn’t even send any parameters which item should be removed cause the second function raised an exception. Can somebody describe a proper solution to add item and delete it after some time?
Sory for not writing it earlier. The exception is
this type of collectionview does not support changes to its sourcecollection from a thread different from the dispatecher thread
If working in WPF use DispatcherTimer. I usually use something like this:
DispatcherTimer will make sure the event is invoked on the same thread so you don’t run into threading issues. Another alternative is to make the collection you’re binding to thread safe. But indeed, knowing what kind of exception you received instead of guessing would be easier.
Also, if you add and remove lots of items in quick succession or require your timing to be precise you’d need to consider something else; DispatcherTimer is not very precise and does carry some overhead, so a lot of instances of it will consume some resources.