Wednesday, December 29, 2010

Waiting for a Save to Complete in an Async Manner

Silverlight is by its design an asynchronous environment.  But sometimes, you really just need to wait for an action to complete before letting the user move on to any other operations.  Ideally, you want to do this in a manner that does not lock the UI thread so that the app is still responsive.  

The best way to do this is to have the method that is doing the action raise an event when the event is complete.  To do this, first declare the event that will be raised, along with any event arguments you want to include with it.

           #region "Events"  
public class SaveCompletedEventArgs : System.EventArgs
public bool SaveSuccessful { get; set; }
public event System.EventHandler<SaveCompletedEventArgs> SaveCompleted;

Then when the Save is completed raise the event (SaveCompleted in this case).

(submitOperation) =>
saveSuccessful = false;
IsBusy = false;
if (!submitOperation.HasError)
saveSuccessful = true;
SaveCompleted(this, new SaveCompletedEventArgs() { SaveSuccessful = saveSuccessful });

Note that in the code above, when the SubmitChanges is run, the program will continue with the next line and return control to the caller.

In the caller, you would do something like the following to handle the event. Use VS2010 to automatically create the event handler for you.

 _ViewModel.SaveCompleted += new EventHandler<ViewModels.AddShoppingListViewModel.SaveCompletedEventArgs>(_ViewModel_SaveCompleted);  

No comments:

Post a Comment