Posts for #C#

I did a presentation recently at the NxtGenUG in Oxford, where I introduced WPF and WCF in a combined session. I created a network enabled implementation of Connect Four to do this. Here’s the download of the demo solution, as requested by some of the attendees:

I have this sample from a recent talk at Basta! conference in Germany, which shows (among other things) how to bind a cross table to a DataGridView (the standard .NET 2 data grid). A cross table is basically the result of transposing some data and using one of the fields for a second dimension.

The sample I have works on two tables of data. It doesn’t actually use a database and the reference that points from the list of votes to that of features is implemented as an object reference, but the relationship is like this:

I recently saw a post in an MS newsgroup and as I had an example that I wrote earlier, I just thought I’d make it available. What this does is simple: it implements custom handling of the non-client area of a window. The non-client area is, normally, the area of a window that is not part of the client area (duh!), like that used for adornments, window buttons, borders, that kind of thing. While the user moves the mouse over a window’s area, Windows sends messages to figure out which part of the window is currently underneath the mouse cursor, and if it finds certain areas, it handles the corresponding functionality itself.

By overriding the default behaviour and returning the right values for these messages, it’s therefore easy to have Windows activate the resize behaviour of the right border, for instance, although the mouse cursor is actually not over the right border at that moment (or even if there isn’t any right border at all). My sample program draws some rects on its client area that “pose” as the borders of the window, as well as the title bar and the resize rect in the lower right hand corner. Looks like this:

In two previous posts (here and here) I have previously posted about how to draw rubber band selection rectangles similar to what Explorer does. Now a reader contacted me by email and asked for an extension: he wants to have a reverse selection, similar to this image:

In a newsgroup I replied to a question about calculating average data throughput during data reception over the network. A simple average bytes per second calculation needs only a few lines of code:

int bytesTotal = 0;
int bytesPerSecond = 0;
DateTime startTime = DateTime.Now;

do {
  bytesRead = receiveStream.Read( ... );
  bytesTotal += bytesRead;
  bytesPerSecond = bytesTotal / (DateTime.Now - startTime).TotalSeconds;

  ...
} while(bytesRead > 0);

This is the eighth article in my mini series about object pooling. Be sure to read part 1, part 2, part 3, part 4, part 5, part 6 and part 7 first. So, although the number of downloads of the sample program hasn’t been exactly great, I’m finally continuing the series. As I said in a previous article, I’d like to factor out the resizing behaviour – but before I do that, I want to integrate functionality that’ll let me evaluate the pool’s performance with regard to resizing, so I can assess the different resizing approaches reliably. Fortunately performance monitoring is something that needs to be integrated into the pool implementation anyway and Windows has all the tools on board. So I only need to configure a few performance counters in Windows, make sure that these counters are updated with current numbers and the Windows performance monitoring frontend is available to the user to show it all in a nice graph. (I’m sure some of you have never heard of the performance monitor application – it’s available on the Administrative tools menu and it’s called, not surprisingly, Performance.) Here’s the download for the current version, including these changes: ObjectPooling-2.zip

Just saw this post in a newsgroup about how to show the horizontal lines that Microsoft likes to use in their dialogs. A lot of people replied with ideas of using other controls, like panels, to achieve the desired effect – to me, a much simpler and more effective idea is to just create a control myself. So, the specific style described by the OP seems to be this:

This is the seventh article in my mini series about object pooling. Be sure to read part 1, part 2, part 3, part 4, part 5 and part 6 first. As some of you may have noticed, I introduced a bad bug in the last article about growing and shrinking, specifically in the code that would call the ExtendPoolBy and ShrinkPoolBy methods. The amount by which to grow or shrink the pool was calculated as the difference between two percentage figures and passed in to the two methods, which really expected absolute values! That’s what I get for not using test-first development on this 😃 So I fixed this and introduced two simple algorithms instead to handle the calculation of the growing and shrinking amounts. This is quite an important topic for object pooling, because it defines how well the pool scales in various scenarios – sometimes it may be desirable to have a pool that adapts quickly to new requirements, sometimes it’s more important to keep the pool size stable as long as possible. In one of the next posts in the series I’m going to factor out the growing/shrinking behaviour using the strategy pattern, until then the current calculation will have to do – and the new test program shows that it doesn’t do that bad at all!

The test program

This is the sixth article in my mini series about object pooling. Be sure to read part 1, part 2, part 3, part 4 and part 5 first. It took me a while to find the time for the next article, but here it is. Now we’re finally going to deal with the topic of growing and shrinking the pool. One of the first questions we have to ask when it comes to this is, when are we going to do it? We have one mechanism for growing the pool implemented already, which takes place when, during a call to the GetObject method, no unused object can be found in the pool. But is this the right place to think about growing, really? And what about shrinking? I think it’s a good idea to keep these things out of the way of “normal call flow”. Meaning, if possible, a client’s call to get an object from the pool shouldn’t be delayed by management work. So I have implemented the mechanism with the help of a timer: a regular check is executed to find whether the number of used objects in the pool is too high or too low and growing or shrinking is done accordingly. To classify the number of used objects as “too high” or “too low”, I’ve introduced two properties HighWaterMark and LowWaterMark. These are percentage values: if the percentage of used objects in the pool is higher than HighWaterMark, the pool is considered too small and vice versa. To prevent the pool size from being scaled up and down wildly in certain scenarios, I have also introduced threshold values – so the percentage has to be found to be too high at more than one check in a row, for example, for the pool to be grown. Actually, the threshold is more useful in the shrinking than the growing case, but it’s the same principle. So, here’s the code for these changes. The next article will introduce a sample program to test all the functionality that’s implemented so far and I’ll post the source code for the pool and the sample with it. So if you haven’t been typing in all this code yourself, stay tuned for the next installment in the series!

class Pool<T> {
  // ...

  private Pool( ) {
    pool = new List<Slot>( );
    retryWaitTime = 500;
    poolExtensionBatchSize = 10;
    poolExtensionBatchSizeIsPercent = true;
    maxGetObjectTries = 5;
    outOfObjectsBehaviour = OutOfObjectsBehaviour.ExtendPool;
    delayObjectCreation = false;
    maxPoolSize = 100;
    lowWaterMark = 20;
    highWaterMark = 80;
    resizingWaitTime = 2000;
    growThreshold = 0;
    shrinkThreshold = 3;
  }

  Timer resizingTimer;
  object resizingTimerLock = new object( );

  private bool useTimerBasedResizing;
  /// <summary>
  /// Gets or sets a value indicating whether the pool checks for low and high
  /// water situations automatically and regularly. Also see ResizingWaitTime.
  /// </summary>
  public bool UseTimerBasedResizing {
    get {
      return useTimerBasedResizing;
    }
    set {
      if (useTimerBasedResizing != value) {
        useTimerBasedResizing = value;
        lock (resizingTimerLock) {
          if (useTimerBasedResizing == false && resizingTimer != null)
            resizingTimer.Dispose( );
          else if (useTimerBasedResizing == true)
            resizingTimer = new Timer(new TimerCallback(ResizingTimerCallback),
              null, resizingWaitTime, Timeout.Infinite);
        }
      }
    }
  }

  private int resizingWaitTime;
  /// <summary>
  /// Gets or sets a value that indicates the time between to checks for low and
  /// high water situations. Also see UseTimerBasedResizing.
  /// </summary>
  public int ResizingWaitTime {
    get {
      return resizingWaitTime;
    }
    set {
      if (resizingWaitTime != value) {
        resizingWaitTime = value;
        lock (resizingTimerLock) {
          if (resizingTimer != null)
            resizingTimer.Change(resizingWaitTime, Timeout.Infinite);
        }
      }
    }
  }

  private int highWaterMark;
  /// <summary>
  /// Gets or sets a value indicating the percentage of used objects in the pool
  /// that must be exceeded for the pool to be grown automatically.
  /// </summary>
  public int HighWaterMark {
    get {
      return highWaterMark;
    }
    set {
      if (highWaterMark != value) {
        highWaterMark = value;
      }
    }
  }

  private int lowWaterMark;
  /// <summary>
  /// Gets or sets a value that the percentage of used objects in the pool
  /// must fall below for the pool to be shrunken automatically.
  /// </summary>
  public int LowWaterMark {
    get {
      return lowWaterMark;
    }
    set {
      if (lowWaterMark != value) {
        lowWaterMark = value;
      }
    }
  }

  private int shrinkThreshold;
  /// <summary>
  /// Gets or sets a value indicating the number of times the pool must
  /// be judged too big before it is shrunken.
  /// </summary>
  public int ShrinkThreshold {
    get {
      return shrinkThreshold;
    }
    set {
      if (shrinkThreshold != value) {
        shrinkThreshold = value;
      }
    }
  }

  private int growThreshold;
  /// <summary>
  /// Gets or sets a value indicating the number of times the pool must
  /// be judged too small before it is grown.
  /// </summary>
  public int GrowThreshold {
    get {
      return growThreshold;
    }
    set {
      if (growThreshold != value) {
        growThreshold = value;
      }
    }
  }

  Slot FindUnusedSlot( ) {
    return pool.Find(delegate(Slot slot) {
      return !slot.InUse;
    });
  }

  /// <summary>
  /// Shrinks the pool size by count elements, at most. The method removes
  /// only unused pool objects, as long as it finds them.
  /// </summary>
  public void ShrinkPoolBy(int count) {
    if (count  0 && unusedSlot != null);
    }
  }

  /// Returns the number of used objects in the pool.
  ///
  public int GetInUseCount( ) {
    int count = 0;
    pool.ForEach(delegate(Slot slot) {
      if (slot.InUse)
      count++;
    });
    return count;
  }

  /// <summary>
  /// Returns the percentage of used objects in the pool.
  /// </summary>
  public int GetFillLevel( ) {
    return GetInUseCount( ) / pool.Count * 100;
  }

  int fillLevelFoundTooLow;
  int fillLevelFoundTooHigh;

  void ResizingTimerCallback(object state) {
    int fillLevel = GetFillLevel( );

    if (fillLevel  highWaterMark) {
      fillLevelFoundTooHigh++;
      fillLevelFoundTooLow = 0;
    }
    else
      fillLevelFoundTooHigh = fillLevelFoundTooLow = 0;

    if (fillLevelFoundTooLow > shrinkThreshold) {
      ShrinkPoolBy(lowWaterMark - fillLevel);
      fillLevelFoundTooLow = 0;
    }
    else if (fillLevelFoundTooHigh > growThreshold) {
      ExtendPoolBy(fillLevel - highWaterMark);
      fillLevelFoundTooHigh = 0;
    }

    lock (resizingTimerLock)
      if (resizingTimer != null)
        resizingTimer.Change(resizingWaitTime, Timeout.Infinite);
  }

  // ...
}

This is the fifth article in my mini series about object pooling. Be sure to read part 1, part 2, part 3 and part 4 first. This part is going to make some modifications to the code in the GetObject method to implement various alternative behaviours there. Think about it: what do you want to happen if there’s no free object to be had in the pool? I came up with the following possible options:

  1. Return null. In this case, the caller would have to deal with the problem further if it can’t get a pool object.
  2. Throw an exception. Really just a variant of (1), because it also pushes the problem out to the caller.
  3. Try again. Because objects are being used and returned to the pool all the time, it might make sense just to wait a bit and try to allocate an object one more time… or two more times, even. A maximum number of tries would be good, I guess.
  4. Extend the pool. The general growing/shrinking discussion hasn’t taken place yet in these articles, but possibly the case where no more objects are available would be a good place to grow the pool.