1

My Silverlight MVVM App's ViewModel Properties that are poupulated from a service library (not WCF Service).

The library method does some operation that may take some time to complete. After the operation is completed the return value is assigned to the ViewModel property.

Since the View is bound to the ViewModel property it would refresh automatically when the Property Value changes. But, during the operation as expected the UI becomes non responsive because its synchronous operation.

How to do the following operation Asynchronously?

Service Contract & Implementation:

public class ItemsLoadedEventArgs : EventArgs
{
    public List<string> Items { get; set; }
}

public interface ISomeService
{
    event EventHandler<ItemsLoadedEventArgs> GetItemsCompleted;

    void GetItemsAsync();
}

public class SomeService : ISomeService
{
    public event EventHandler<ItemsLoadedEventArgs> GetItemsCompleted;

    public void GetItemsAsync()
    {
        // do something long here
        // how to do this long running operation Asynchronously?
        // and then notify the subscriber of the Event?

        // when the operation is completed fire the event
        if(this.GetItemsCompleted != null)
        {
            this.GetItemsCompleted(this, new ItemsLoadedEventArgs { Items = resulthere });
        }
    }
}

ViewModel:

public class HomeViewModel : ViewModel
{
    private ISomeService service;
    private ObservableCollection<string> _items;
    // Items property is bound to UI
    public ObservableCollection<string> Items
    {
        get { return this._items; }
        set 
        {
            this._items = value;
            this.RaisePropertyChanged(() => this.Items);
        }
    }

    // DI
    public HomeViewModel(ISomeService service)
    {
        ...

        this.service = service;

        // load items
        this.LoadItems();
    }

    private void LoadItems()
    {
        this.service.GetItemsCompleted += (s, ea) =>
        {
            this.Items = new ObservableCollection<string>(ea.Items);
        };

        this.service.GetItemsAsync();
    }
}

Problem:

Since the data is loaded in the constructor, and the operation is synchronous it makes the UI unresponsive.

How to perform the operation inside the GetItemsAsync method of the SomeService class Asynchronously?

Zuhaib
  • 1,420
  • 3
  • 18
  • 34

1 Answers1

1

Use Dispatcher.BeginInvoke to call your library method. You have to go back to the UI thread to update your ViewModel when it is done. See this question for info on this.

Community
  • 1
  • 1
Timores
  • 14,439
  • 3
  • 46
  • 46
  • Thanks. I was able to do it with the help of following two articles. [SmartDispatcher](http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/) [Threading Sample](http://www.andrewshough.com/development/silverlight/asynchronous-tasks-in-silverlight/) – Zuhaib Mar 24 '11 at 11:32