Archive

Posts Tagged ‘lambdas’

Black Belt C# Series - Syntax

April 4th, 2009

The Black Belt C# series aims to uncover powerful but lesser-known features of the C# language. Each article introduces a few of these features and shows you how to use them to take your programming to the next level.
 

The “??” Operator

This granule of syntactical sugar, known as the the “Null Coalescing Operator”, provides a quick way to check and react to null values. As an example, lets say we have a widget name which came from an external source. Programming defensively, it’s always good idea to check reference types for null before working with them. Here’s an example of the code that may be written without using the operator:

 

   1: string WidgetName = DivineWidgetNameFromEther();
   2: 
   3: if (WidgetName != null)
   4: {
   5:     System.Diagnostics.Debug.WriteLine(WidgetName);
   6: }
   7: else
   8: {
   9:     System.Diagnostics.Debug.WriteLine("WidgetName is null");
  10: }
(10 Lines, 294 Characters)
 
 
This first example branches off into two nearly identical paths. This redundancy is an innocent mistake, but can add up quickly in a large project. There are a few ways you could go about refactoring this, let me show you the best method in this case:
 
   1: string WidgetName = DivineWidgetNameFromEther();
   2: 
   3: System.Diagnostics.Debug.WriteLine(WidgetName ?? "WidgetName is null");
(3 Lines and 124 Characters)

 

This, vastly superior version, produces identical output to the first. If WidgetName is not null, then it’s simply written to the output window. However, if WidgetName does happen to be null, “WidgetName” is null” is safely written instead. This is a great way to unobtrusively improve quality in your program without sacrificing readability.

 

Black Belt Tip: Lazy Instantiation Made Easy

Leverage the null coalescing operator to achieve lazy instantiation with manually implemented properties:

   1: private List<Widget> _Widgets = null;
   2: public List<Widget> Widgets
   3: {
   4:     get { return _Widgets ?? (_Widgets = new List<Widget>()); }
   5: }

 

 

Automatic Properties

Auto-Implemented properties are a nice shorthand (C# 3+) for expressing a public property and a private (although inaccessible) field… without having to type all of that out. Have a look:

 

   1: /// <summary>
   2: /// This is a valid property and NOT a field.
   3: /// </summary>
   4: private string WidgetDescription { get; set; }

 

This is a perfectly valid property, backed by a private field that is created automatically but is inaccessible. Here is the disassembly:

 

   1: .property instance string WidgetDescription
   2: {
   3:     .get instance string BlackBeltCSharp.Form1::get_WidgetDescription()
   4:     .set instance void BlackBeltCSharp.Form1::set_WidgetDescription(string)
   5: }
   6: 
   7: 
   8: .field private string <WidgetDescription>k__BackingField
   9: {
  10:     .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
  11: }
(k__BackingField and the get_…() and set_…() methods are generated automatically by the compiler)
 

You can designate a different scope for the getter and for the setter, without leaving automatic properties. For Example:

   1: public string WidgetDescription { get; private set; }
…is perfectly valid and renders the property read-only from outside of the current class.
 
 
 

Advanced Generics

Taking advantage of generics, introduced in .NET 2.0, is a great way to improve your productivity while layering on type-safety and added performance benefits (up to 200% when working with value types such as integers). To review, here is a sample generic method and usage:

Sample Generic Method
   1: /// <summary>
   2:  /// Selects and returns an item at (pseudo)random from the supplied list
   3:  /// </summary>
   4:  /// <typeparam name="T">Any Type</typeparam>
   5:  /// <param name="FromList">Source list from which to pick an item from</param>
   6:  /// <returns>(pseudo)Randomly selected item</returns>
   7:  private T SelectRandom<T>(List<T> FromList)
   8:  {
   9:      Debug.Assert(FromList != null, "FromList (of type " + typeof(T).Name + ") is null.");
  10: 
  11:      //Picks a pseudo-random index in "FromList"
  12:      int RandomlySelectedIndex =
  13:          new Random((int)(DateTime.Now.Ticks % 0x7FFFFFFF)).Next(FromList.Count);
  14: 
  15:      //Returns item at randomly chosen index
  16:      return FromList[RandomlySelectedIndex];
  17: 
  18:  }
 
Sample Usage
   1: List<String> Names = new List<String>() { "Daniel Dennett", "John Locke", "Saul Kripke" };
   2: List<int> Numbers = new List<int>() { 2, 5, 7 };
   3: 
   4: Debug.WriteLine("Read " + SelectRandom<int>(Numbers) +
   5:     " books from " + SelectRandom<string>(Names));

The usage outputs something like “Read 7 books from John Locke”. The important thing to notice is the use of the same generic “SelectRandom” method for both integers and strings.

 

Type Inference

It’s possible for the c# compiler to infer the type to be used. For example, this is perfectly legal:

   1: Debug.WriteLine("Read " + SelectRandom(Numbers) +
   2:     " books from..." + SelectRandom(Names));

 

Where T : new()

This special constraint limits acceptable types to those which feature a public, parameterless constructor. This allows for some really special syntax inside a generic class. Have a look:

   1: class ConstrainedGenericClass<T> where T : new()
   2: {
   3:     private T NewItemOfTypeT = new T();
   4: }

 

Using the “new()” constraint unlocks the ability to easily instantiate a new version of the specified class type. This is just the tip of the iceberg, for a complete list of constraints, visit:

http://msdn.microsoft.com/en-us/library/6b0scde8(VS.80).aspx

 

Currying

Likely the most advanced and confusing topic surrounding generics in c#, currying is the process of distributing an argument list over several functions, instead of one. For example, instead of having one function that takes three arguments, you can have three functions taking one argument, each building on the next. Let me show you a few examples:

 

Example Without Currying
   1: private void DoWork()
   2: {
   3:     //Outputs 11
   4:     Debug.WriteLine(AddNumbers(1, 3, 7));
   5: }
   6: 
   7: //Returns sum of three integers
   8: private int AddNumbers(int X, int Y, int Z)
   9: {
  10:     return X + Y + Z;
  11: }

 

Example With Currying
   1: private void DoWork()
   2: {
   3:     var CurriedNumberAdder = Curry(AddNumbersWork);
   4: 
   5:     //Outputs 11
   6:     Debug.WriteLine(CurriedNumberAdder(1)(3)(7));
   7: }
   8: 
   9: Func<int,int,int,int> AddNumbersWork = (X, Y, Z) => X + Y + Z;
  10: 
  11: //Standard Curry Function
  12: private Func<T1, Func<T2, Func<T3, T4>>> Curry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> function)
  13: {
  14:     return a => b => c => function(a, b, c);
  15: }

If you haven’t yet delved into functional programming then this example may be confusing and the benefit may not be immediately obvious. What’s happening here is each function calls the next, while contributing its argument. This process continues until it gets to the last function (X + Y + Z), which in this case defines what should happen with the arguments that have been assembled.

There are a few interesting benefits to this massive overhead of complexity. First, it’s possible to slowly assemble the function in bits and pieces over many lines. Example:

Example of Calling One Argument at a Time
   1: private void DoWork()
   2: {
   3:     var CurriedNumberAdder = Curry(AddNumbersWork);
   4: 
   5:     //...Do Something Else Here
   6: 
   7:     var FirstResult = CurriedNumberAdder(1);
   8: 
   9:     //...Do Something Else Here
  10: 
  11:     var SecondResult = FirstResult(3);
  12: 
  13:     //Outputs 11
  14:     Debug.WriteLine(SecondResult(7));
  15: }

 

This may be useful for reducing the scope and span of variables that contribute to your curried function. More importantly, by encapsulating combinations of arguments inside a variable, it opens up new possibilities for reuse:

Example Reusing Curried Functions
   1: private void DoWork()
   2: {
   3:     var CurriedNumberAdder = Curry(AddNumbersWork);
   4: 
   5:     var FirstResult = CurriedNumberAdder(1);
   6:     var SecondResult = FirstResult(3);
   7: 
   8:     //Outputs 5
   9:     Debug.WriteLine(SecondResult(1));
  10: 
  11:     //Outputs 14
  12:     Debug.WriteLine(SecondResult(10));
  13: 
  14:     //Outputs 104
  15:     Debug.WriteLine(SecondResult(100));
  16: }

Share/Save/Bookmark

Black Belt, C# , , , , , , ,

Threading Tips and Tricks

January 11th, 2009

 

too-much-threading

Have you ever had trouble designing or debugging multi-threaded applications?

 

Asynchronous programming can be a struggle without a toolbox of techniques and tips to help. Let me show you what I’ve learned to make multi-threading in C# faster to implement and easier to manage!

 

Use the Threads Window

Visual Studio (Standard and up) has a tool for viewing running threads, aptly named the “Threads” window (Start your application in the debugger and then click on Debug->Windows->Threads [or CTRL+D, T]. Break execution to activate the window. From there, you can see which threads are running and minimal information about each one.

threads-window2

The really useful feature about the Threads window is that it allows you to update the call stack window to the thread of your choosing. Just double click on another thread to synchronize the call stack window with the new thread.

thread-menu

Another useful feature is the ability to Freeze and Unfreeze threads without using the Immediate window. Just right click on a given thread to pull up the relevant menu.

Freezing other threads is exceptionally useful if you are trying to step through execution in just one thread and it’s safe to temporarily ignore the others.

Without freezing the other threads, the debugger is likely to move you around from the context of one thread to another while stepping through, wasting your time and energy in the process.

 

Name your threads.

Use the Thread.Name property to assign a descriptive name to each of your threads. For Example:

   1: Thread YearEndProfitReportThread = new Thread(CreateYearEndProfitReport);
   2: YearEndProfitReportThread.Name = "Year End Profits Calculator";
   3: YearEndProfitReportThread.Start();

 

Now, in the Threads window you will be able to see the name you assigned instead of “<No Name>”.

threads-window-named

This is useful while debugging, because of instead of selecting each thread until you find the right one you can jump to exactly the one you need.

 

Leverage the power of C# 3.0

Language specification 3 introduced a few powerful tools such as object initializers and lambda expressions that can apply to threading. These are very powerful tools that obviously need to weighed carefully with readability and maintainability but can dramatically cut down on the amount of code to write.

Note: Parameterless lambdas are only being used here because they are slightly more succinct than using anonymous methods.

Quick and (Very) Dirty Example

   1: (new Thread(() => {
   2:     DoLongRunningWork();
   3:     MessageBox.Show("Long Running Work Finished!");
   4: }) { Name = "Long Running Work Thread",
   5:     Priority = ThreadPriority.BelowNormal }).Start();

 

In only five lines of code, we create a new thread, give it some work to do (via parameterless lambda expression), assign the name and priority (thanks to object initializers) and then trigger it to start. This example assumes reasonable exception handling in the DoLongRunningWork() method and should be wrapped in a try…catch {} block to catch exceptions such as ThreadAbortException (See below for Exception Handling tips).

 

More Practical Example, Hide a Form for X Time

Taking advantage of closures (introduced in 2.0), we can build functions with arguments that are automatically available inside inline lambda statements. Have a look at this example, which hides a form for a certain timespan:

 

   1: private void MakeInvisible(TimeSpan Duration) {
   2:  
   3:     (new System.Threading.Thread(() =>
   4:     {
   5:         try
   6:         {
   7:             this.Invoke(new MethodInvoker(this.Hide));
   8:             System.Threading.Thread.Sleep(Duration);
   9:         }
  10:         catch (ThreadAbortException ThreadAbort)
  11:         {
  12:             //...
  13:         }
  14:         catch (ThreadInterruptedException ThreadInterrupt)
  15:         {
  16:             //...
  17:         }
  18:         finally
  19:         {
  20:             this.Invoke(new MethodInvoker(this.Show));
  21:         }
  22:     }) 
  23:     { 
  24:         Name = "MakeInvisible (" + Duration.ToString() + ")" 
  25:     }
  26:     ).Start();
  27:  
  28: }

 

Using the lambda statement, we are providing the set of instructions to run in our new thread and using property initializers towards the bottom of the function we are setting the thread name. Closures are used with the this keyword and Duration – both of which are passing through to the lambda statement automatically from the host method (MakeInvisible).

Although a bit poor on readability, I think this is a great example of how 3.0 and threading can replace a swath of other (much more complicated) code. To write the same example without the latest language features would take at least a timer and one more method, as well as additional code to wire everything together.

 

Use Airtight Exception Handling

In production applications, it pays you to have the most extensive error handling possible in all of your worker threads. Have a look at the following unsafe code example:

   1: private void UnsafeButton_Click(object sender, EventArgs e)
   2: {
   3:  
   4:     int x = 0;
   5:     int y = 1 / x;
   6:  
   7: }

If you were to start this application outside of the debugger and press the button, at worst you would receive the following dialog box:

divide-by-zero

Bad, but life goes on (via the Continue button). Now, if that same unsafe code is put in a worker thread:

   1: private void UnsafeButton_Click(object sender, EventArgs e)
   2: {
   3:     (new Thread(()=> {
   4:         int x = 0;
   5:         int y = 1 / x;
   6:     })).Start();
   7: }

You are asking for trouble. This is what happens:

stopped-working

The entire application shuts down without details about the exception or a way to continue. (This won’t happen inside the debugger, of course). An alternative to wrapping all of your worker threads in try…catch blocks is to handle the Application.ThreadException Event. This is a quicker way to ensure that your application won’t come to grinding halt when an exception is thrown in a worker thread.

As a final note, be aware that threads are susceptible to the special exceptions ThreadAbortException and ThreadInterruptedException. It’s possible to cancel an initiated abort by handling ThreadAbortException and calling ResetAbort() in the catch block.

Share/Save/Bookmark

C#, Tips and Tricks , , , , , ,