0

Is it good solution for updating ObservableCollection? Are there any dangers hiding in this code?

namespace WpfApplication142
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            DataContext = new GetData();
            InitializeComponent();
        }
    }
    public class GetData
    {
        public ObservableCollection<string> Items {get;set;}
        public GetData()
        {
            Items = new ObservableCollection<string>();
            Items.Add("one");
            var task = Task.Factory.StartNew(() =>
                {
                    UpdateItems();
                });
            task.ContinueWith(delegate { Items.Add("two"); }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
        }
        public void UpdateItems()
        {
            System.Threading.Thread.Sleep(10000);
        }
    }
}

Xaml code look like this

<Grid>
    <ListView ItemsSource="{Binding Items}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding .}"></Label>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>
Muds
  • 4,006
  • 5
  • 31
  • 53
A191919
  • 3,422
  • 7
  • 49
  • 93
  • Constructors shouldn't do async stuffs. You should have a service that raise an event when new data are available or call a function in your Service layer that retrieve data. Plus, if you want to display the ObservableCollection you'll want to create that ObservableCollection in the Dispatcher thread. – nkoniishvt Sep 02 '15 at 09:02
  • in what thread ObservableCollection collection creates in example? – A191919 Sep 02 '15 at 09:11
  • In the Dispatcher thread. Problem is you uses it in your Task, but your task is executed in another thread so it'll raise an exception saying that the current Thread doesn't own the ObservableCollection. – nkoniishvt Sep 02 '15 at 09:14
  • Try to build, there is no exceptions – A191919 Sep 02 '15 at 09:17
  • Take particular note of [this answer](http://stackoverflow.com/a/14602121/109702). – slugster Sep 02 '15 at 09:59
  • @slugster He's not updating the Observablecollection from another thread. TaskScheduler.FromCurrentSynchronizationContext() grabs the right Dispatcher in this case. – Martijn Sep 02 '15 at 10:07
  • 1
    @MartijnvandenH So it does... that pesky bit of code is scrolled out of sight.... in any case the links I left him help to validate his approach. I'll delete my comment as I can't edit it. – slugster Sep 02 '15 at 10:19

0 Answers0