I want is to remove a Notification
from a ObservableCollection<Notification>
after some timeout. Is there a better way than starting a new ThreadPool thread for each added item and Thread.Sleep
in there?
Final code based on Nidonocu's answer:
public class NotificationCollection : ObservableCollection<Notification>
{
private readonly DispatcherTimer timer;
public NotificationCollection()
: this(Application.Current.Dispatcher)
{
}
public NotificationCollection(Dispatcher dispatcher)
{
this.timer =
new DispatcherTimer(DispatcherPriority.DataBind, dispatcher);
this.timer.Tick += this.TimerOnTick;
}
protected override void InsertItem(int index, Notification item)
{
base.InsertItem(index, item);
if (!this.timer.IsEnabled)
{
this.StartTimer(item);
}
}
private void StartTimer(Notification item)
{
var timeout = item.Timestamp + item.Timeout - DateTime.UtcNow;
if (timeout < TimeSpan.Zero)
{
timeout = TimeSpan.Zero;
}
this.timer.Interval = timeout;
this.timer.Start();
}
private void TimerOnTick(object sender, EventArgs e)
{
this.timer.Stop();
this.RemoveAt(0);
if (this.Count > 0)
{
this.StartTimer(this[0]);
}
}