using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Windows; using System.Windows.Threading; namespace WpfApp1 { public class TestViewModel { public ObservableCollection Children { get; set; } = new ObservableCollection(); } public partial class MainWindow : Window { public TestViewModel ViewModel = new TestViewModel(); public MainWindow() { InitializeComponent(); DataContext = ViewModel; for (int i = 0; i < 4; i++) { new Thread(UpdateChildren) { IsBackground = true }.Start(); } } private void UpdateChildren() { var mtid = Thread.CurrentThread.ManagedThreadId; Random random = new Random(mtid); int i = 0; var its = new List(); while (true) { if ((its.Count == 0) || (random.Next() % 2 == 0)) { var it = $"{mtid}-{++i}"; its.Add(it); Dispatcher.BeginInvoke((Action)delegate { ViewModel.Children.Add(it); }); } else { var index = random.Next(its.Count); var it = its[index]; its.RemoveAt(index); Dispatcher.BeginInvoke((Action)delegate { ViewModel.Children.Remove(it); }); } Thread.Sleep(random.Next(2)); } } } }