C#, EF Entity Framework, Generics, RIA Services, Silverlight

Executing RIA Service Calls One-At-A-Time

Without going into details (because I’m not allowed to), I’m working on a RIA services app where one page has a large data-bound collection of buttons. Each button toggles a state, on or off. When the button is clicked, a RIA service call is performed to modify the state of the bound data, which sets the button state to Busy, setting a BusyIndicator to busy. When the callback returns, the busy state is turned off, and the details on the button are updated to reflect the change in data that I requested. While the button is “busy”, you’re not able to click it again until the callback is executed, which then re-enables the button. This list of buttons is in a wrap panel, and in my scenario, it represents a list of 1000+ objects whose state can be toggled on or off.

Everything was working very well, except if you clicked more than one button without waiting for the previous button’s callback to execute. On my local network, the callback time is very small (well under one second), but I could easily click a bunch of buttons really quickly, which would in turn cause RIA services to try to execute more than one call to update data at a time, which is not allowed.

InvalidOperationException: A SubmitChanges operation is already in progress on this DomainContext.

That throws a wrench in my gears! My options were:

  1. Add a BusyIndicator to the wrap panel, and setting it to be busy after each click;
  2. Try to get the calls to execute one-at-a-time by queuing them.

The first option was considered, but the problem there is that no other button could be toggled while the RIA service was running. Speed in clicking buttons in this list is key, and having the whole wrap panel be busy and not busy would make it flash a lot, and it’s just not as clean as having the RIA service calls execute in a queue.

My ExecuteOneAtATimeQueue class takes care of queuing RIA service calls, or any other asynchronous calls that can only run one-at-a-time such as WebClient.

Class code:

 

using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;

namespace Derreck Dean
{


 // item being modified
 // item in queue
 // function to execute

 // 1. Object is added to the queue...
 //    a. Item (userstate) being modified
 //    b. Function defining how to load image

 internal class ExecuteOneAtATimeQueue : IDisposable, INotifyPropertyChanged
 {
 public ObservableCollection<ExecuteOneAtATimeQueueItem> Queue = null;

 public event EventHandler QueueItemWorkStarted;
 public event EventHandler QueueItemWorkCompleted;
 public event EventHandler AllQueueItemsCompleted;

 private NotifyCollectionChangedEventHandler ncceh;
 private bool canProcessQueue = false;

 public ExecuteOneAtATimeQueueItem CurrentItem {
 get {
 return _currentItem;
 }
 internal set {
 _currentItem = value;
 OnPropertyChanged("CurrentItem");
 }
 }
 private ExecuteOneAtATimeQueueItem _currentItem;

 /// <summary>
 /// Init
 /// </summary>
 public ExecuteOneAtATimeQueue() {
 ncceh = new System.Collections.Specialized
 .NotifyCollectionChangedEventHandler(Queue_CollectionChanged);
 Queue = new ObservableCollection<ExecuteOneAtATimeQueueItem>();
 Queue.CollectionChanged += ncceh;
 }

 public void BeginProcessingQueue() {
 canProcessQueue = true;
 if (Queue.Count > 0)
 processQueue();
 }

 /// <summary>
 /// Adds an item to the queue.
 /// </summary>
 /// <param name="queueItem"></param>
 public void Add(ExecuteOneAtATimeQueueItem queueItem) {
 queueItem.WorkStarted += new EventHandler(queueItem_WorkStarted);
 queueItem.WorkCompleted += new EventHandler(queueItem_WorkCompleted);
 queueItem.PropertyChanged += 
 new PropertyChangedEventHandler(queueItem_PropertyChanged);
 lock (Queue) {
 Queue.Add(queueItem);
 }
 }

 /// <summary>
 /// Called when the item in the collectiom changes
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void queueItem_PropertyChanged(object sender, PropertyChangedEventArgs e) {
 processQueue();
 }

 /// <summary>
 /// Adds work to the queue.
 /// </summary>
 /// <param name="itemToModify">Item being modified and returned.</param>
 /// <param name="userState">Optional extra data to be passed in; can be null.</param>
 /// <param name="method">Void function taking in queue item, 
 /// itemToModify and userState.</param>
 public void Add(object itemToModify, object userState, 
 Action<ExecuteOneAtATimeQueueItem, object, object> method) 
 {
 ExecuteOneAtATimeQueueItem qi = new ExecuteOneAtATimeQueueItem(itemToModify, userState);
 qi.DoWork = method;
 Add(qi);
 }

 internal void queueItem_WorkCompleted(object sender, EventArgs e) {
 if (QueueItemWorkCompleted != null) { QueueItemWorkCompleted(sender, e); }
 //processQueue(); // Continue processing queue
 }

 internal void queueItem_WorkStarted(object sender, EventArgs e) {
 if (QueueItemWorkStarted != null) { QueueItemWorkStarted(sender, e); }
 }

 /// <summary>
 /// Process the contents of the queue, if we are able.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Queue_CollectionChanged(object sender, 
 System.Collections.Specialized.NotifyCollectionChangedEventArgs e) 
 {
 processQueue();
 }

 /// <summary>
 /// Processes the queue if we're allowed, and starts work if we are able to.
 /// </summary>
 internal void processQueue() {
 if (canProcessQueue) {
 // See if there are any busy items in the queue. 
 // If there is not, then pop one off the stack and start executing it.
 // If there are no more items in the queue, we're finished.
 bool areAnyBusy = Queue.Any(qq => qq.IsBusy == true && qq.IsCompleted == false);
 var workToDo = Queue
 .Where(qq => qq.IsBusy == false && qq.IsCompleted == false).ToList();
 if (!areAnyBusy && workToDo.Count > 0) {
 var q = workToDo.First();
 q.StartWork();
 // Done in Item object: if (QueueItemWorkStarted != null) { 
 QueueItemWorkStarted(q, null); 
 }
 } else {
 // See if everything has been completed
 if (Queue.All(qq => qq.IsCompleted == true)) {
 if (AllQueueItemsCompleted != null) { 
 AllQueueItemsCompleted(this, new EventArgs()); 
 }
 }
 }
 }
 }

 /// <summary>
 /// Queue item for work to complete.
 /// </summary>
 internal class ExecuteOneAtATimeQueueItem : INotifyPropertyChanged
 {

 /// <summary>
 /// Time work was started.
 /// </summary>
 public DateTime? StartedWork {
 get { return _startedWork; }
 internal set {
 _startedWork = value;
 OnPropertyChanged("StartedWork");
 OnPropertyChanged("IsBusy");
 OnPropertyChanged("IsCompleted");
 }
 }
 private DateTime? _startedWork = null;

 /// <summary>
 /// Time work was completed, with or without errors.
 /// </summary>
 public DateTime? EndedWork {
 get { return _endedWork; }
 internal set {
 _endedWork = value;
 OnPropertyChanged("EndedWork");
 OnPropertyChanged("IsBusy");
 OnPropertyChanged("IsCompleted");
 }
 }
 private DateTime? _endedWork = null;

 /// <summary>
 /// The item that is being worked on
 /// </summary>
 public object ItemToModify { get; set; }

 /// <summary>
 /// Another object passed to DoWork that can be modified/used
 /// </summary>
 public object UserState { get; set; }

 /// <summary>
 /// Describes if the current item is busy or not.
 /// We know this if startedWork is null or if endedWork is not null.
 /// </summary>
 public bool IsBusy {
 // IsBusy: Work has started but not completed
 get { return (_startedWork != null && _endedWork == null); }
 }

 /// <summary>
 /// Returns true if the work for this queue item has been completed.
 /// </summary>
 public bool IsCompleted {
 get { return (_startedWork != null && _endedWork != null); }
 }

 // Describes if there was a problem running the function or not.
 public bool IsError {
 get { return _isError; }
 set { _isError = value; OnPropertyChanged("IsError"); }
 }
 private bool _isError = false;

 ////////////////////////////////////////////////////////////////////////////////////////

 internal bool _hasWorkCompletedEventBeenRaised = false;

 internal event EventHandler WorkCompleted;
 internal event EventHandler WorkStarted;

 ////////////////////////////////////////////////////////////////////////////////////////

 public ExecuteOneAtATimeQueueItem() { }
 public ExecuteOneAtATimeQueueItem(object itemToModify) {
 this.ItemToModify = itemToModify;
 }
 public ExecuteOneAtATimeQueueItem(object itemToModify, object userState) {
 this.ItemToModify = itemToModify;
 this.UserState = userState;
 }

 /// <summary>
 /// Function that is called to begin work on an item.
 /// The ExecuteOneAtATimeQueueItem.EndWork() method must be called at the 
 /// end to mark the queue item as completed.
 /// The first object is the object being modified.
 /// The second object is extra stuff that can be passed in to aid in the work being run.
 /// </summary>
 public Action<ExecuteOneAtATimeQueueItem, object, object> DoWork { get; set; }

 /// <summary>
 /// Called when work ends and the queue item can be marked as done.
 /// </summary>
 /// <param name="isError"></param>
 /// <param name="userState"></param>
 public void EndWork(bool isError, object userState) {
 EndedWork = DateTime.Now;
 this.IsError = isError;
 if (!_hasWorkCompletedEventBeenRaised) {
 if (WorkCompleted != null) { WorkCompleted(this, new EventArgs()); }
 _hasWorkCompletedEventBeenRaised = true;
 }
 }

 /// <summary>
 /// Called when work is started.
 /// </summary>
 public void StartWork() {
 if (this.IsBusy)
 throw new InvalidOperationException("Work has already started for this item.");
 StartedWork = DateTime.Now;
 if (WorkStarted != null) { WorkStarted(this, new EventArgs()); }
 if (DoWork != null) { DoWork(this, ItemToModify, UserState); }
 }

 #region INotifyPropertyChanged Members

 public event PropertyChangedEventHandler  PropertyChanged;

 internal void OnPropertyChanged(string s) {
 if (PropertyChanged != null) {
 PropertyChanged(this, new PropertyChangedEventArgs(s));
 }
 }

 #endregion
 }


 #region IDisposable Members

 public void Dispose() {
 Queue.CollectionChanged -= ncceh;
 Queue = null;
 }

 #endregion

 #region INotifyPropertyChanged Members

 public event PropertyChangedEventHandler  PropertyChanged;

 private void OnPropertyChanged(string s) {
 if (PropertyChanged != null) {
 PropertyChanged(this, new PropertyChangedEventArgs(s));
 }
 }

 #endregion
 }

}

Using The Class

Using the class is pretty easy. First, create a queue object in your viewmodel or control:

 

 private ExecuteOneAtATimeQueue queue;

Initialize the queue when you’re ready to use it:

 

 queue = new ExecuteOneAtATimeQueue();
 queue.BeginProcessingQueue();

BeginProcessingQueue() instructs the queue to start processing whatever items it already has or receives immediately. You can pre-populate the queue and then call BeginProcessingQueue(), or do what I did and just start adding items whenever you like.

So here’s my offending code, which failed when the buttons were clicked too fast:

void setObjectState(...) {
 ...
 Reference.ObjectData.SubmitChanges(so => { // BOOM
 if (callback != null) {
 if (so.HasError) {
 so.MarkErrorAsHandled();
 }
 callback(userState, so.Error);
 }
 }, true);
 ...
 }

 

Here’s the change to that call that was made, to queue it up and execute it.

 

 void setObjectState(...) {
 ...
 queue.Add(null, null, (qi, item, us) => {
 Reference.ObjectData.SubmitChanges(so => {
 if (callback != null) {
 if (so.HasError) {
 so.MarkErrorAsHandled();
 }
 callback(userState, so.Error);
 }
 qi.EndWork(so.HasError, null);
 }, true);
 });
 ...

}

I didn’t need to pass in any objects to modify during the callback, so I set both to null. In the queue.Add(…) statement, “qi” refers to the internal class instance ExecuteOneAtATimeQueueItem, which you must call EndWork() to tell the queue to move onto the next QueueItem instance and begin work. “item” and “us” (for user state) are both null, since nulls were passed in as the first two parameters to the Add() method. You can pass in two objects to work with if you need, I didn’t need them here though.

With this class, I added five lines of code to queue up RIA service calls, although your mileage may vary. Now I’m not disabling the whole wrap panel, I’m only setting each button instance to busy/disabled until the callback is called.