About the author

Brian Keating is a developer addicted to Microsoft Technologies.

Month List

RecentComments

Comment RSS

Converting EPM operations to Tasks using the TPL

clock February 5, 2012 11:41 by author Brian Keating |

 

Previous post

Overview

The Event Programming Model (EPM from her on in) was introduced in .NET 2.0, it’s purpose was to serve as a simpler pattern for asynchronous operations than the Asynchronous Programming Model (APM / IAsyncResult, see my previous post on APM) where possible, mostly in UX code. Methods that use this pattern typically end in Async and have a Completion event.

The best known implementation of the EPM is the BackgroundWorker component, it’s got a distinct advantage in that it tries to use a synchronization context to fire the event on the thread from which it was called, the APM on the other hand offers no such guarantee.

Let’s see this in action (.net 4.0)


image

What you can see in the snippet above is a simple windows form (been a while my old friend) application. Let me paint you a picture, it’s early February 2012 and I’m stuck here at Brussels international airport, in the middle of a snow blizzard wondering if I’m going to have a flight home. The plane that will take me there is arriving in from Dublin so I’m looking at the live departures to see if it’s departed (already 15 mins late darn it.. ) anyway back to the post at hand; I’m downloading the page html with the call to DownloadStringAsync(), you can see in the completion event handler that I’m not doing any Invoking (dispatching to those of you that never had the pleasure of windows forms).

Now this is what it looks like after the event gets fired.

image

hey and looks like it’s running MS tech (notice that viewstate, incase the .aspx didn’t give it away!) nice! If you come from a web background this may not seem that odd to you, but if you started out desktop application development like me there was one golden rule you never forgot and that’s that always talk to the GUI in one thread and one thread only.

If the event handler wasn’t in the GUI thread above we would have received a cross thread exception like this:

image

 

Sadly TPL doesn’t handle the EPM as easily as the APM specifically in respect to the synchronization context, but lets see how we approach it, you may have to if you’re pre .net 4.0 as the DownloadStringAsync doesn’t exist!

image

With the code above we hit the cross-thread exception problem. We could do a Control.BeginInvoke (or Dispatcher.BeginInvoke in WPF), but lets imagine we were writing a library and we wanted it to be framework agnostic, how would we do this?

Actually it’s pretty simple, we just supply a context like this:

image

p.s. I got home at 4am Sad smile




Converting APM operations to Tasks using the TPL

clock January 1, 2012 12:47 by author Brian Keating |

 

Those of you have have already used .net 4.5 developer preview will know that tasks are becoming more common in the API, especially with the advent of the async await keywords.

But many of you (including me) can’t really advocate .net 4.5 in the enterprise so what are our options should we like to use the TaskParallelLibrary?

As you may be aware APM (Asynchronous Programming Model) was the original .NET mechanism for handling Async operations, it will be familiar to you as the IAsyncResult pattern.

So lets take a common operation of reading from a stream, in .net 4.5 we already have a Stream.ReadAsync, but again what if we don’t have .net 4.5 at our disposal?

The task parallel library helps bridge the gap with Task.Factory.FromAsync, here I place it in an extension method for ease of use.

image




scoped_ptr in C#

clock August 5, 2011 23:22 by author Brian Keating |

 

Is there a better way? Or at least a more generic way to leverage the dispose pattern? Well here’s one I thought of tonight

 

   1:      public class ScopeMngr : IDisposable
   2:      {        
   3:          private Action _dispose = null;
   4:   
   5:          public ScopeMngr(Action init, Action dispose)
   6:              : this(dispose)
   7:          {
   8:              init();            
   9:          }
  10:   
  11:          public ScopeMngr(Action dispose)
  12:          {
  13:              _dispose = dispose;
  14:          }
  15:   
  16:          public void Dispose()
  17:          {
  18:              if (_dispose != null)
  19:              {
  20:                  _dispose();
  21:                  _dispose = null;
  22:              }
  23:          }
  24:      }

Sample usage:

   1:      public partial class Form1 : Form
   2:      {
   3:          public Form1()
   4:          {
   5:              InitializeComponent();
   6:          }
   7:   
   8:          private void button1_Click(object sender, EventArgs e)
   9:          {
  10:              using (var sm = new ScopeMngr(() => Cursor = Cursors.WaitCursor, () => Cursor = Cursors.Default))
  11:              {
  12:                  Thread.Sleep(TimeSpan.FromSeconds(10));
  13:              }
  14:   
  15:              bool updating = false;
  16:              using (var sm = new ScopeMngr(() => updating = true, () => updating = false))
  17:              {
  18:                  // updating is true here
  19:                  // update the UX etc.
  20:              }
  21:              // updating is false here
  22:   
  23:          }
  24:      }

 

P.s. I know creating an object to reset a boolean is a bit of overkill, but see my comments and argument for same in my c++ post 


Enjoy.

p.s. you could also just use a try {} finally {}




“Knock, knock.” -- “Who’s there?” -- long wait... -- “Java.”

clock June 13, 2011 00:09 by author Brian Keating |

 

So whose faster? Well C# or Java if you are talking “RAD”, but who executes faster?

IMO, C# and Java can be just as fast or faster because the JIT compiler (JIT or just in time is a compiler that compiles your IL the first time it's executed). JIT compiler can make optimizations that a C++ compiled program cannot because it can query the machine. It can determine if the machine is Intel or AMD; Pentium 4, Core Solo, or Core Duo; or if supports SSE4, etc.

A C++ program has to be compiled beforehand usually with mixed optimizations so that it runs decently well on all machines, but is not optimized as much as it could be for a single configuration (i.e. processor, instruction set, other hardware).

Additionally certain language features allow the compiler in C# and Java to make assumptions about your code that allows it to optimize certain parts away that just aren't safe for the C/C++ compiler to do. When you have access to pointers there's a lot of optimizations that just aren't safe.

Also Java and C# can do heap allocations more efficiently than C++ because the layer of abstraction between the garbage collector and your code allows it to do all of its heap compression at once (a fairly expensive operation).

Now I can't speak for Java on this next point, but I know that C# for example will actually remove methods and method calls when it knows the body of the method is empty. And it will use this kind of logic throughout your code.

So as you can see, there are lots of reasons why certain C# or Java implementations will be faster.

Now this all said, specific optimizations can be made in C++ that will blow away anything that you could do with C#, especially in the graphics realm and anytime you're close to the hardware. Pointers do wonders here.

Of course, C# (or Java, or VB) is usually faster to produce viable and robust solution than is C++ (if only because C++ has complex semantics, and C++ standard library, while interesting and powerful, is quite poor when compared with the full scope of the standard library from .NET or Java), so usually, the difference between C++ and .NET or Java JIT won't be visible to most users, and for those binaries that are critical, well, you can still call C++ processing from C# or Java (even if this kind of native calls can be quite costly in themselves).




INotifyPropertyChanged diagnostics

clock May 13, 2010 21:41 by author Brian Keating |

Those of you that use INotifyPropertyChanged may have noticed it's easy to break the code if you choose to refactor/rename as the property name string does not get refactored.

Here is a mechanism to catch this problem at the implementation stage.

 

#region Debugging Aides

/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
    // Verify that the property name matches a real, 
    // public, instance property on this object.
    if (TypeDescriptor.GetProperties(this)[propertyName] == null)
    {
        string msg = "Invalid property name: " + propertyName;

        if (this.ThrowOnInvalidPropertyName)
            throw new Exception(msg);
        else
            Debug.Fail(msg);
    }
}

/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get; private set; }

#endregion // Debugging Aides

#region INotifyPropertyChanged Members

/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };

/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
    this.VerifyPropertyName(propertyName);
    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));           
}

#endregion // INotifyPropertyChanged Members