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?