简体   繁体   English

从计时器内部的ListBox中删除

[英]Removing from ListBox inside of a Timer

ObservableCollection<String> listBoxItems = new ObservableCollection<String>();
scheduledRecordingListBox.ItemsSource = listBoxItems;

public void timerElapsed(object sender, ElapsedEventArgs e)
{
    listBoxItems.Remove(itemToBeRemoved);
}

Just a snippet of what I'm actually trying to do. 只是我实际上正在尝试做的一小段。 I believe the error is caused because the timer is running on a different thread than the GUI main thread that the ObservableCollection I'm trying to remove from is. 我相信是由于计时器在与我要从中删除的ObservableCollection的GUI主线程不同的线程上运行而导致的错误。

If you are using WinForms, then just use the System.Windows.Timer class. 如果使用的是WinForms,则只需使用System.Windows.Timer类。 It's Tick event is automatically executed on the UI thread. 它的Tick事件在UI线程上自动执行。

Try using Invoke it executes a delegate on the thread that owns the control's underlying window handle. 尝试使用Invoke,它在拥有控件的基础窗口句柄的线程上执行委托。

You can also have a look of the section timers in this page 您也可以在此页面中查看部分计时器

This should do the Trick: 这应该做的把戏:

public void timerElapsed(object sender, ElapsedEventArgs e)
{
    this.Invoke(new Action(() => listBoxItems.Remove(itemToBeRemoved)));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM