Alex
Alex

Reputation: 294

Multi-threading windows phone application

I want to make getting data make loading not in the ui thread but in background thread. I've tried several examples from google, but it's still not working.

ThreadPool.QueueUserWorkItem((o) =>
{
    IList<Asana> asanasRepo = null;
    var asanasRepository = this.GetService<IAsanasRepository>();
    asanasRepo = asanasRepository.GetAllAsanas();

    Asanas = asanasRepo.Select(x => new AsanasListItemViewModel
    {
        AsanaId = x.AsanaId,
        AsanaLevel = InfrastructureHelper.GetLevel(x.AsanaLevel),
        CoverImagePath = string.Format("/Content/Images/{0}", x.CoverImageFileName),
        UsualAsanaTitle = x.UsualTitle,
        YogaAsanaTitle = x.YogaTitle
    }).ToObservableCollection();

    asanasDispatcher.BeginInvoke(() =>
    {
        AsanasItems.Clear();
        AsanasItems = (from asana in Asanas
                       group asana by asana.AsanaLevel into c
                       orderby c.Key
                       select new Group<AsanasListItemViewModel>(c.Key, c)
                      ).ToObservableCollection();
    });
});

The main idea is lo load data from database not in the ui thread, but in background, when the data will be loaded render it to the ui. I've tried something like the piece of code above, but it's not working. Can you help me with this? Thank you!

Upvotes: 4

Views: 757

Answers (1)

Igor Kulman
Igor Kulman

Reputation: 16361

Try initializing AsanasItems to an empty ObervableCollection<..> in the constructor and in your shown code do not assign a new collection to it, just use AsanasItems.Add(..) to add items one by one.

If it does not work you need to provide a minimal working sample for anyone to be able to help you.

Upvotes: 3

Related Questions