Category Archives: WPF

Enforcing Single Application Instances in WPF with Named Pipes

In some cases, we may wish to prevent the user from starting multiple instances of applications. Instead, the existing (single) instance should be focused. The “single instance” part is pretty easy, but notifying the first instance to come to the front is more tricky. There are many attempts to demonstrate techniques for this around the net, but I found them difficult and unreliable in WPF. In particular, they mostly all depend on using WndProc broadcast messages which are only received when the target window is not minimized, and even then not reliably. Further, there would be no way to actually send any data (like a command line) from the new instance to the original instance.

Rather than continue to struggle with this unproductive path, I took a step back and thought about what I wanted to do: I want to send a message from one instance of an application to another. Isn’t that what named pipes are for?

I created an abstraction based on mutexs (to enforce single instancing) and named pipes (to communicate between instances) that easily allows an application to ensure only a single instance is used. The abstraction could easily be expanded to allow for passing data to the single instance.

Get it on GitHub

To use this abstraction, omit a StartupUri from App.xaml and override OnStartip in the App.xaml.cs:

public partial class App : Application
{
  protected override void OnStartup(StartupEventArgs e)
  {
    // Set a unique application ID
    Guid id = Guid.Parse("DC2A927C-AC89-4512-BB29-7AB0A18DE105");

    // Instantiate an SIA
    SingleInstanceApplication sia = new SingleInstanceApplication(id);            
    // Handle the ApplicationStarts event
    // When this event fires, initialize the application
    sia.ApplicationStarts += (sender, earg) =>
    {
      var mw = new MainWindow();
      mw.Show();
      // If another instance attempts to start, 
      // bring our window to the front
      sia.AnotherInstanceAttemptsToStart += 
        SingleInstanceApplication.BringToFrontWhenCalled(mw);
    };
    // Optionally handle AnotherInstanceAttemptsToStart, for example, 
    // to log other attempts
    sia.AnotherInstanceAttemptsToStart += (sender, earg) =>
    {
      Logger.LogInfo("### Captured another instance trying to start");
    };
    // Run the application and single instance protection
    sia.RunSingleInstance();            
  }

Handling Performance Issues with INotifyPropertyChanged and Expensive PropertyChanged Event Handlers

Consider the case of an object which implements INotifyPropertyChanged and has properties that may be dependent on each other. You may have a circumstance where a single user command causes several properties to change, and, depending on the object’s implementation, may generate several PropertyChanged events. If an event handler for the object’s PropertyChanged event executes an expensive or UI intensive task, the multiple PropertyChanged events can cause a real performance problem.

One approach to this problem is to “batch” the PropertyChanged events, combining any duplicate notifications, and dispatch them as a single event after some quiet timeout. The quiet timeout can be very small to maintain the appearance of responsiveness while still capturing multiple change events into a single event dispatch.

I constructed a static class “AccumulatedPropertyChangeNotification” with two public methods: AddHandler, and RemoveHandler. These methods allowed an event handler to be attached to an INotifyPropertyChanged, indirectly, through the accumulator. In order to appropriately handle accumulated property changes (which could be more than one property), I created an event type which supports a sequence of changed properties.

public class AccumulatedPropertyChangedEventArgs : EventArgs 
{
    /// <summary>
    /// A distinct list of properties changed within the last notification cycle. If any notification
    /// of ""/null (meaning possibly all properties) has been submitted, then this property will be null.
    /// </summary>
    public IEnumerable<string> Properties {get;set;}
}

In order to accumulate dispatches, I used a timer which checks which events are queued and, when appropriate, dispatches them in bulk. This means that the AccumulatedPropertyChanged event is dispatched on a different thread than the object that generated the original PropertyChanged event. To address this situation, I also allow listeners to supply an optional ISynchronizeInvoke for the timer.

Adding and removing handlers are performed with these signatures:

public static void AddHandler(INotifyPropertyChanged objectToWatch, AccumulatedPropertyChangedHandler handler, ISynchronizeInvoke syncObject = null);
public static void RemoveHandler(INotifyPropertyChanged objectToWatch, AccumulatedPropertyChangedHandler handler);

When a handler is added, the handler is added to an internal notification list, and the PropertyChanged event of the objectToWatch is wired to an internal handler in the AccumulatedPropertyChangeNotification class. This handler simply puts the event, and the time it occurred, into an internal event queue.

private static List<Tuple<INotifyPropertyChanged, AccumulatedPropertyChangedHandler, ISynchronizeInvoke>> notifications;
private static List<Tuple<INotifyPropertyChanged, PropertyChangedEventArgs, DateTime>> changeNotificationsQueued;

When the timer fires, it looks at the change notification queue, groups by INotifyPropertyChanged instance, and checks for the most recent DateTime of property changed. If it is at least as old as the mandatory delay (by default, 50 milliseconds), then all the changes for that instance are batched and dispatched to all AccumulatedPropertyChangedHandler delegates associated with that object. This was a bit tricky to get correct.

The other issue that was tricky was RemoveHandler, doing a lookup on a given handler to remove it. Apparently Object.ReferenceEquals with methods doesn’t work well (or didn’t for me), so I ended up using .Equals on the delegate, which is not (still isn’t) what I expected to do.

Download implementation and unit tests. You will probably want to change the namespace to match your project.

If you’re using WPF, you’ll need a wrapper for the Dispatcher to implement ISynchronizeInvoke (come on Microsoft, get your shit together). A good implementation can be found at http://blogs.openspan.com/2010/04/hosting-openspan-a-complete-isynchronizeinvoke-wrapper-for-the-dispatcher/, though beware I found that InvokeRequired was returning false when it should have been returning true.

Model Validation with Data Annotations and Metadata Classes in WPF

In the ASP.NET MVC world, Microsoft has provided an interesting technique for data validation: data annotations. Data annotations are lightweight, and, using Metadata classes (shown in the previous link), data annotations can be applied effortlessly to entity framework or datatset generated models (for database-first uses).  This technique has been very convenient for our EF/MVC applications.

What about WPF applications?

Suddenly the waters get murky.  When using data binding with WPF, supported validation techniques include:

None of these fit well with data annotations.  However, there is a way forward: the blog post “Data Validation in WPF” includes a bit on implementing data annotations with the help of a validator class.  Unfortunately, this approach does not support metadata classes!

To work with generated data classes and metadata model validation in WPF, I have extended the above exchange to support validation rules in metadata classes.  In this way, you can share your metadata validation rule classes between WPF and MVC applications with no changes.

Implementation

For the model class that you want to provide data annotation support to, extend it with a partial class implementing INotifyDataErrorInfo.  The implementation is completely boilerplate, and you could extend your code generator template to include it. For this example, my model class is called “Bridges”, as it is directly derived from the table of that name in the database. I’ll assume we’re going to add a metadata class called “BridgesValidation” to validate some aspects of this model.

To begin with, we can create a partial class for the model, adding an interface for INotifyDataErrorInfo and attaching the metadata class in the usual way (the same way you would with EF database first).

[MetadataType(typeof(BridgesValidation))]
public partial class Bridges :  INotifyDataErrorInfo

Next, we need to provide the interface event, and prepare a dictionary for storing which fields are in error. The method will simply lookup in the dictionary to see if the requested property is in error.

public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
private Dictionary<string, string> errorsForName = new Dictionary<string, string>();

public System.Collections.IEnumerable GetErrors(string propertyName)
{
   if (errorsForName.ContainsKey(propertyName))
      return new string[] { errorsForName[propertyName] };
   else
      return new string[0];
}

How (and when?) to calculate which fields are in error? I created a calculate errors method, which I attached to the column changed event notification for the model (which derives from DataRow). You could just as easily attach to the property changed event notification for the model. Depending on how the model is implemented (DataRow, EF, etc) the exact attachment procedure will vary. In any case, however, a boilerplate error calculation routine can be used.

The process for this routine is:

  1. Clear all existing errors
  2. Acquire all metadata class types
  3. For each property and each metadata class, find any validation attributes
  4. Apply validation attributes and save errors

First, clear all existing errors. If deriving from DataRow, could also call “ClearErrors” here.

errorsForName.Clear();

Second, acquire all metadata class types (this is the interesting bit that the above link does not include).

var types = this.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), false)
                          .OfType<MetadataTypeAttribute>()
                          .Select(mta => mta.MetadataClassType);

Finally, look through all classes and all properties to find any validation attributes. When the “Add” is called on errorsForName, if using a DataRow derivative, that would be a good time to call “SetColumnError” as well.

        foreach (Type t in types.Union(new Type[] { this.GetType() }))
        {
            foreach (var prop in t.GetProperties())
            {
                var validations = prop.GetCustomAttributes(true).OfType<ValidationAttribute>().ToArray();
                foreach (var val in validations)
                {
                    var propVal = this[prop.Name];
                    if (!val.IsValid(propVal))
                    {
                        var errMsg = val.FormatErrorMessage(prop.Name);
                        errorsForName.Add(prop.Name, errMsg);
                        if (ErrorsChanged != null)
                            ErrorsChanged(this, new DataErrorsChangedEventArgs(prop.Name));
                    }
                }
            }
        }

Now you are ready to use data annotation validations in WPF!

Simply use the same kind of data annotation metadata class as you would for an ASP.NET MVC application, and use the above partial class template to extend each generated model class file. WPF will pick up the INotifyDataErrorInfo, which will in turn provide a seamless link between the metadata class data annotations and the WPF user interface.

Preventing Memory (and Time!) Leaks in WPF with Weak Events

Normally in .NET the garbage collector eliminates any concern we might have regarding memory leaks.  However, there are certain cases where “lost” objects may be retained because references to them still exist.  One possible mechanism for this is event wiring.

Imagine the case where a host component, like a main application window, contains an object which can notify of changes.  The main window instantiates a child component, and sets a property on the child to the observable component.  The child component then begins to listen for changes.  This adds a reference to the child window to the listener collection of the observable component.  Since the observable component is long-lived, that reference will persist.  If the child component is created and destroyed many times, a noticeable memory leak may result.

Let’s create a simple main and child components (in this case, windows). The main window will own the reference to the observable item. The child window will accept it as a property, and listen for changes on it. Very important to note that these components do not need to be windows; they can be any created and destroyed component.

Here’s a framework for the main window:

public partial class MainWindow : Window
{
   private ObservableCollection items;

   public MainWindow()
   {
      InitializeComponent();
      items = new ObservableCollection();
      items.Add(5);
      items.Add(7);
   }

   public void ShowCloseOtherWindow()
   {
      Window1 w = new Window1 { Items = items };
      w.Show();
      w.Close();
   }
}

And here’s a framework for the child window. Notice I am omitting the event wiring, which will occur in the setter. This is the point of difference and where weak events will come into play. The assumption is some control is databound to the Sum property and will receive notifications of changes via Window1’s PropertyChanged event.

public partial class Window1 : Window, INotifyPropertyChanged
{

   private ObservableCollection _items;
   public ObservableCollection Items
   {
      get
      {
         return _items;
      }
      set
      {
         _items = value; 
         // TODO: Wire this to notify collection changed
      }
   }

   public int Sum { get; protected set; }

   void _items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
   {
      Sum = Items.Sum();
      if (PropertyChanged != null)
         PropertyChanged(this, new PropertyChangedEventArgs("Sum"));
   }

   public event PropertyChangedEventHandler PropertyChanged;
}

For testing purposes, we can rig up a simple timer on the main window which will create and close many child windows. The timer will simply invoke ShowCloseOtherWindow every, say, 250 ms or so. We can then monitor the memory usage of the application with different notification techniques. To monitor memory usage, I’m using perfmon on the specific process. To monitor performance, I’m using a Stopwatch instance around a call to .Add in the main window. This Add occurs every 30 seconds. When the Add (or any other change) occurs, the observable collection notifies all listeners. The time taken to notify all listeners is monitored by the stopwatch.

To establish a baseline, I will start with the empty implementation of the Items setter. This is obviously unacceptable in practice, since it does not result in changes (or even the original value) of the Items being exposed to the Sum calculator.

In this diagram, overall app memory (blue) and time to add item (red) are indicated. Overall memory usage increases slightly over time (as expected), since items are continually added to the collection. Since the collection is never actually listened to or processed in any way, time to add stays relatively flat.
NoEventListen - Copy

A Naive Implementation

Now assume we want Window1 to listen to the collection for changes, and when changes occur, to recalculate the value of Sum. We can modify the setter of Items:

if (_items != null)
{
   _items.CollectionChanged -= _items_CollectionChanged;                    
}
_items = value;
_items.CollectionChanged += _items_CollectionChanged;

This seems very reasonable: it ensures that the items collection can be changed, and that extraneous events will not cause a recalculation. Nevertheless, this implementation hides a dangerous flaw: By adding the listener, the items collection now has a reference to the component (in this case, an instance of Window1). If the component is intended to be discarded, the garbage collector will not collect it because a reference still exists (from the items collection). This causes a memory leak if many instances are created and then discarded. Furthermore, since the “zombie” components are still listening for changes and still recalculate the Sum on changes, as more and more instances are created (and zombified), the processing overhead of adding values will increase dramatically, causing a time leak.

Let’s run the program again, with the same instrumentation on memory (blue) and time (red). Notice how both skyrocket quickly (time usage even increases polynomially). The flat line of memory at the end is where the program crashed!
EventListenDefault

Hopefully you can see how aggressive this kind of memory/time leak can be and how insidiously difficult to locate it it might be in a large and complex program!

How to Fix

The “obvious” solution is to use IDisposable and dispose of the object, having the Dispose method remove the event listener. In some cases, disposing of objects is tricky and we want to allow the garbage collector to work. For the remainder of this article, I will assume we want to find a garbage collectable solution.

Problems with garbage collection can sometimes be addressed using “weak references”. A weak reference tells the garbage collector not to count that particular reference when considering whether an object can be freed or not. Thus, if we modify the event handler above so that it is a weak reference, the garbage collector will still be able to collect it, and the problem (both time and space) will go away.

However, this is not as trivial as it seems. Although .NET has a WeakReference class, this class only supports object references, not delegates (and by extension, not event handlers). What we really need is a “weak event” mechanism.

Several solutions exist. In general, an intermediate static object which maintains the weak references and dispatches events as appropriate is needed. In many cases, developers have needed to write these classes themselves. For example, see the detailed Weak Event Handlers blog entry by Steven Hollidge.

In WPF, Microsoft has provided a framework of this sort in the .NET library through WPF weak events. This implementation makes it very easy for WPF developers to use weak events. Although the documentation on weak events is somewhat confusing, the generic WeakEventManager is sufficient and can be easily used in place of a traditional unsubscribe/subscribe model. We modify the Items setter as follows:

if (_items != null)
{                    
   WeakEventManager<ObservableCollection<int>, NotifyCollectionChangedEventArgs>.RemoveHandler(
      _items, "CollectionChanged", _items_CollectionChanged);
}
_items = value;                
WeakEventManager<ObservableCollection<int>, NotifyCollectionChangedEventArgs>.AddHandler(
   _items, "CollectionChanged", _items_CollectionChanged);

There is no need to modify the event handler or write any other boilerplate code.

The result? Memory usage and time increase slowly as items are added to the collection (which is exactly the expected behavior). The time increase is due to the calculation of sum which now occurs, whereas in the first graph, since the event handler was never wired, no sum calculation ever occurred.
EventListenWeak

Download the complete WPF Weak Reference demo source code, including both techniques and instrumentation.

A comprehensive article dealing with weak events in all their facets is available by Daniel Grunwald.