Wednesday, August 25, 2010

Handling Leaking Handles




If Handle count reaches more than 5000 count, whole PC might freeze and become unresponsive.

In the Event Log, you might have seen: “The server was unable to allocate from the system nonpaged pool because the pool was empty” message before system frozen.


This application had many wpf third party components, events and ui updates that were happening every 5 seconds, including tree updates. And it was leaking handles.

I verified that by cycling major logical parts, handle leak was not happening. But it happened when the whole flow was executed. When in debug mode, following the flow, leak does not happen. This was timing related.



Short Story Shorter, this is how I fixed it. Calling GC.Collect(2, GCCollectionMode.Forced) on each cycle fixed the leak. Yes, you would say that eventually GC should collect the thread. Here is a relevant issue that other people reported. And Microsoft defect that had to do with how GC cleans up unused threads, this is what they say:

“The problem is that CLR thread handles (and other associated data structures) are cleaned up by the finalizer thread, which normally only runs in response to a garbage collection (GC). If many threads are created and destroyed before a GC occurs (which would be the case if there were few memory allocations in the meantime) then it has the effect of "leaking" handles and memory, althgough these will be reclaimed the next time finalization is triggered. A workaround is to periodically manually trigger finalization, through calls to GC.WaitForPendingFinalizers. As I said, we are working to correct this in a future CLR release.“ –Microsoft.


Solution 1:

So if you are in a long run leaking handles, see if GC.Collect(2, GCCollectionMode.Forced)  fixes it. If not, then you deal with logical gaps. Readon further.


Solutions 2,3,4,..:

Possible Leak Causes:


What does NOT leak Handles:

  • Extra subscriptions to Events do not lead to leaking Handles
  • Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart((), does not leak handles. Verified.



Close or Dispose on StreamWriter related objects? In most cases, it is more appropriate to Dispose it instead of Close, it depends, see article Close vs. Dispose.


More about Handles.

Tuesday, August 10, 2010

if This, Then else That


If Else statements are the major part of Coding. These are the roads that split and divert the streams of logic. The point that I want to tackle here is about how phrasing the “If Else” statements can influence the mindset of writer and reader of the code. The claim that I would make is that “If” statements are better be phrased in positive term. And the operations in “If” block, are better be handling the main, a general, a positive flow of logic. And the rest is for “Else” block.

Thus, developer is concentrating first on positives and only then on negatives. Goal first, diligence second. Main flow first, edge cases second. Wall first, coloring it second.



If (something)


   do this




  do that



By concentrating first on the positive aspect helps person to get into the subject of the statements. “do this” communicates the context, a pathway towards some goal, and “do that” communicates the edge case, a complimentary addition to “do this”. There can not be This without That. This and That go together. What’s more important? This or That? Both? What’s the prioritization?This first, That second, isn’t it?

Friday, July 2, 2010

.Net App Crushes on Windows Server 2003? user-defined breakpoint?


are you in trouble?



some possible causes might be calling Debugger.Break();, clean them up.


Another case reported, here, no resolution though.

Another idea, catch(Exception) vs catch, more here, did not help for me.

Another fact, if you would debug this application remotely, this “user-defined breakpoint” symptom disappears. For remote debugging, see here.

In this particular case, the cause was the null references.

The hunt is still on on the real cause.

Wednesday, May 26, 2010

SelectedItem disables associated Buttons



Situation: There is a List, and some buttons that are ought to act on current selected item in the list. But if there are no items or no item is selected then you want these buttons to be disabled.

The idea: Having buttons disabled/enabled implicitly/automatically based on the currently selected item in the list.

  1. <Style x:Key="disableIfNoListItemSelected" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
  2.   <Style.Setters>
  3.     <Setter Property="UIElement.IsEnabled" Value="True" />
  4.   </Style.Setters>
  5.   <Style.Triggers>
  6.     <DataTrigger Binding="{Binding SelectedIndex}" Value="-1">
  7.       <Setter Property="UIElement.IsEnabled" Value="False" />
  8.     </DataTrigger>
  9.   </Style.Triggers>
  10. </Style>


  1. <Button Name="cmdShow"
  2.                     DataContext="{Binding ElementName=grdTemplates}"
  3.                     Style="{StaticResource disableIfNoListItemSelected}">
  4.                 </Button>

Notice in the usage, when applying a style to a button, it is required to assign a DataContext of this button to the List that is being watched.

Tuesday, May 18, 2010

Closing Modal Dialog Window in WPF


If it is a modal dialog box, then it most probably has OK, Cancel buttons. If it has OK, Cancel buttons, them most probably the “client initiator” wants to know if Ok was pressed or not.


Remember WinForms had DialogResult enumeration? It is a bit different with WPF, ShowDialog() returns bool?.

bool? result = form.ShowDialog();if (result.HasValue && result.Value){ DoMyThing();}

When will result.Value be false?  Make sure that you do this only for True/Ok case, the default is false:

private void Ok_Click(..){ this.Close(); this.DialogResult = true;}

and one more thing. To close dialog on Esc, you want this:


For OK button you want this:


This way, when user presses Enter, OK button is pressed.


Warning about IsCancel and Cancel button. There seems no way to Cancel the “Cancel event”. So if user clicks Cancel, windows is going to be closed. If you know a way for canceling the closure, please post.

Wednesday, May 12, 2010

Implicitly “degrading” ui controls


If this is valuable then mostly as an idea for now. Current implementation might be too limited and can be further enhanced.

The goal is to hide or disable ui controls if they do not show anything, or whatever they show is missing. Degrades=Hide or Disable.

In WPF terms and in this cut, I’ve made that ui control becomes hidden or disabled automatically if when DataContext becomes null. This implies that host has to be bound to something real, and presence of that real thing implicitly degrades(or not) the host.

Styles from Resources
  1. <Style x:Key="hideStackPanelIfNull" TargetType="StackPanel" BasedOn="{StaticResource {x:Type StackPanel}}">
  2.     <Style.Setters>
  3.       <Setter Property="UIElement.Visibility" Value="{x:Static Visibility.Visible}" />
  4.     </Style.Setters>
  5.     <Style.Triggers>
  6.       <DataTrigger Binding="{Binding}" Value="{x:Null}">
  7.         <Setter Property="UIElement.Visibility" Value="{x:Static Visibility.Hidden}" />
  8.       </DataTrigger>
  9.     </Style.Triggers>
  10.   </Style>
  12.   <Style x:Key="disableButtonIfNull" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
  13.     <Style.Setters>
  14.       <Setter Property="UIElement.IsEnabled" Value="True" />
  15.     </Style.Setters>
  16.     <Style.Triggers>
  17.       <DataTrigger Binding="{Binding}" Value="{x:Null}">
  18.         <Setter Property="UIElement.IsEnabled" Value="False" />
  19.       </DataTrigger>
  20.     </Style.Triggers>
  21.   </Style>
  23.   <Style x:Key="disableStackPanelIfNull" TargetType="StackPanel" BasedOn="{StaticResource {x:Type StackPanel}}">
  24.     <Style.Setters>
  25.       <Setter Property="UIElement.IsEnabled" Value="True" />
  26.     </Style.Setters>
  27.     <Style.Triggers>
  28.       <DataTrigger Binding="{Binding}" Value="{x:Null}">
  29.         <Setter Property="UIElement.IsEnabled" Value="False" />
  30.       </DataTrigger>
  31.     </Style.Triggers>
  32.   </Style>

Usage Example
  1. <StackPanel DataContext="{Binding ElementName=myList, Path=SelectedItem}"
  2.           VerticalAlignment="Center" Orientation="Horizontal"
  3.           Style="{StaticResource hideStackPanelIfNull}">
  4.     <TextBlock Text="Name:"></TextBlock>
  5.     <TextBlock Text="{Binding Path=Name}"></TextBlock>
  6. </StackPanel>


In this example StackPanel is bound to SelectedItem. If there is nothing in the list, SelectedItem becomes null and that degrades the controls that bear presented here styles, textblocks become disabled or hidden.

Some caveat. Obviously this requires to overwrite your style. It might conflict with your style requirements. In above shown example I am pointing to StackPanels which usually do not need style.



WPF binding binds one thing to another based on default conversion. For fancier conversion there is Converter. With Converter you can map more than one things to one thing.

User List in a Combo Box
  1.     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  2.     {
  3.         string name = string.Empty;
  4.         if (value is MyUser)
  5.         {
  6.             MyUser user = value as MyUser ;
  7.             name = string.Format("{0}{1}[{2}]", user.FirstName, user.LastName, user.ZipCode.ToString());
  8.         }
  9.         return name;
  10.     }… …<local:UserNameConverter x:Key="userNameConverter"/>
  11. <ComboBox>
  12.   <ComboBox.ItemTemplate>
  13.     <DataTemplate>
  14.       <StackPanel Orientation="Horizontal">
  15.         <TextBlock Text="{Binding Converter={StaticResource userNameConverter}}" />
  16.       </StackPanel>
  17.     </DataTemplate>
  18.   </ComboBox.ItemTemplate>
  19. </ComboBox>



Some Advanced Converters on is here.