Using Dispatcher.Invoke() and the asynchronous method:

 public async void InitObservableCollection() { var listFromDAL = await Dispatcher.Invoke(() => Context.GetListAsync()); listFromDAL.ToList().ForEach(i => MyObservableCollection.Add(new Model(i))); } 

Or without it, launching the synchronous method via Task.Factory.StartNew() :

  public async void InitObservableCollection() { var listFromDAL = await Task.Factory.StartNew(() => Context.GetList()); listFromDAL.ToList().ForEach(i => MyObservableCollection.Add(new Model(i))); } 

Both options work, I do not see much difference.

  • And you measured it, the difference then? - Monk
  • @Monk, no, did not measure. Just as far as I know, Dispatcher.Invoke () executes the method passed to it in the delegate synchronously. So what's the point if you can use Task. Or does Task also block the calling thread? - klutch1991

1 answer 1

Dispatcher.Invoke is not a task in the background thread at all - but a return from the background stream to the UI stream. That is, this method actually does the exact opposite of what you need.

Task.Factory.StartNew , like Task.Run , is the launch of a task in another thread. It would be possible to use this option if there were no easier option.

But for some reason you didn’t guess the simplest option. No need to invent anything, everything is already implemented!

 public async void InitObservableCollection() { var listFromDAL = await Context.GetListAsync(); listFromDAL.ToList().ForEach(i => MyObservableCollection.Add(new Model(i))); }