简体   繁体   中英

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.

If you are using WinForms, then just use the System.Windows.Timer class. It's Tick event is automatically executed on the UI thread.

Try using Invoke it executes a delegate on the thread that owns the control's underlying window handle.

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)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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