Tag Archives: refactoring

Analyzing events usage using a R# plugin

As you might already know, even if the .Net framework has a garbage collector, you can easily create memory leaks in your application.

The most common way to create a leak is to register to an event handler on a object that has a longer lifetime than the object where the handler is defined. The problem can also occurs by using static class such as EventManager (for more information see this blog post). Some .Net developers have been working on a way to go round the problem using Reflection, Weak Reference and other cool stuff. You can check out for example this excellent article on Code Project.

However, if you cannot change the way your declare events (because of internal policies in the company or because you don’t have the source code), you must be very carefull about the way you manage your events.

I’ve been working lately on a Resharper plugin that helps detecting events that are never unsubscribed. Basically, what is does is the following:

resharper_plugin

I’d like to have feedback from you .Net developpers, about whether you find such a plugin useful or not.

  • How do you deal with the event memory leak problem ?
  • Would you like to use my plugin ?
  • Would you like me to release it on a open source platform ?
  • What other kind of possible leaks are you thinking about to enhance the plugin ?

Please write a comment to let my know what you think. Thank you for your feedback !

The cost of building Visual Trees

In the current project I’m working on, I’m designing a diagramming component. Of course because it’s for work I can’t release the source code (however if you want a good starting point you can check out this article). Designing such a component is a challenging task and there are a number of things I learned during the last few months that I’m glad to share here.

As you problably know the WPF engine manages 2 trees: the logical tree and the visual tree. For each logical item (that you declare in the XAML), the item is expanded with its visual tree (for example, a scrollbar is made of RepeatButtons and a Thumb). To visualize the visual tree you can use a tool like snoop.

In a diagramming tool, you might want to draw lines betweeen entities, like the following:

connection

In this article, we’re going to talk about the underlying control that we can use to do that. If you need to create that kind of control, you basically have 2 options:

  • inherits from Control and override the OnRender method to do the basic graphic operations (such as drawing a line or an ellipse)
  • inherits from Control and create a ControlTemplate to fill the visual tree of your control

Of course the first option has better performance, but it’s also less evolutive. Moreover, in the OnRender method, you can only do low level graphic operations.

Using the second option is generally fine and easy:

  1. create the class that inherit from Control
  2. create a style that targets your new control
  3. add a Setter to set the ControlTemplate property
  4. fill the ControlTemplate’s content

Here is a sample ControlTemplate for a basic connection (assuming that the Connection class has 4 double dependency properties (X1,Y1) (X2,Y2) that defines that start and the end point):

1
2
3
4
5
6
7
8
9
10
11
12
<Style TargetType="{x:Type VisualTreePerf:Connection}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type VisualTreePerf:Connection}">
          <Line X1="{TemplateBinding X1}" Y1="{TemplateBinding Y1}"
                  X2="{TemplateBinding X2}" Y2="{TemplateBinding Y2}"
                  Stroke="Black" StrokeThickness="2">                                
          </Line>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Of course this is a very minimal template, you’re probable going to improve it by adding new features:

  • 2 rectangles to show the extremities of the connection
  • 2 thumb to be able to drag’n’drop the extremities
  • 1 context menu to access connection’s operations

You can do that by adding more controls to the template. Now, take a second and think about the performances. Time is needed to built and render the visual tree and the most complex it is, the longer it takes. I did a quick benchmark on my machine and here are the results for 500 connections added in a Canvas:

performance

What we can see is that adding only 5 controls in the template, we multiply the rendering time by 4 ! That means we must be careful when we’re designing ControlTemplate that are going to be instantiated many time. Before creating the control we should think about whether the control is going to by displayed 1, 10, 100 or 1000 times in our application. More complex ControlTemplates mean more time to render them. Several techniques can be used to improved performance:

  • use a panel that supports UI virtualization (such a VirtualizingStackPanel)
  • use adorners to give feedback while an item is selected to improve creation performance (create the Adorner only when the item is selected)

To explore other performance related techniques:

Why do I love Extension Methods in System.Linq ?

Because it helps me to write compact and clean code of course !

For example, I need to expose a property that gives the number of visible items in my ViewModel.

Old way:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
        public int VisibleItemsCount
        {
            get
            {
                int i = 0;
                foreach (var item in this.Items)
                {
                    if (item.IsVisible)
                        i++;
                }
                return i;
            }
        }

Linq way:

?View Code CSHARP
1
2
3
4
5
6
7
public int VisibleItemsCount
{
    get
    {
        return this.Items.Count(item => item.IsVisible);
    }
}

Which one do you prefer ?