Je souhaite supprimer un Notification
à partir d'un après un certain délai. Y a-t-il une meilleure façon que de commencer un nouveau thread ThreadPool pour chaque élément ajouté et Thread.Sleep
là?Suppression d'un élément d'une collection après un certain délai
code final basé sur réponse de Nidonocu:
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]);
}
}
Pourriez-vous donner un exemple? Toutes mes tentatives d'utilisation d'un seul thread ont échoué, principalement parce que les éléments doivent être supprimés dans le thread principal. – dtb
Travailler dessus ... – Nidonocu
Merci. Je l'ai modifié un peu et posté le résultat dans la zone de question. – dtb