Checking for null arguments in a method is not a very glamorous programming task, but it can be worth the time investment.  Instead of your code reacting to a null argument at some unexpected place (and throwing a NullReferenceException), you can be more proactive and check for null arguments at the beginning of the method and throw an ArgumentNullException yourself.

For example, say we have a method called PostIt that takes two arguments – a URI of a web page, and an XML document to post to it.  In this case, neither of these arguments should be null, so we can check for valid arguments like this:

public void PostIt(Uri uri, XmlDocument document)
{
    if (uri == null)
        throw new ArgumentNullException("uri");

    if (document == null)
        throw new ArgumentNullException("document");

    // Arguments are good -- continue...
}

There’s nothing wrong with this approach, but writing code like this everywhere can become a bit tedious.  Furthermore, the above code is not immune to refactoring.  Renaming the method’s arguments will not change the literal passed into the exception’s constructor.

To make things a bit easier and more immune to refactoring, I created a static helper method that takes one or more lambda expressions, checks each for null, and throws an ArgumentNullException when it encounters one.

This is what the PostIt method looks like using the helper method:

public void PostIt(Uri uri, XmlDocument document)
{
    Helper.CheckArgumentNull(() => uri, () => document);

    // Arguments are good -- continue...
}

Instead of four lines of code, we have one.  Furthermore, renaming the arguments will rename the variables in the lambda expression.

Here’s the code:

public static void CheckArgumentNull(
    params Expression<Func<Object>>[] exprs)
{
    foreach (var expr in exprs)
    {
        if (expr.Compile().Invoke() == null)
            throw new ArgumentNullException(
                (expr.Body as MemberExpression).Member.Name);
    }
}

The CheckArgumentNull method uses the params keyword to allow for a variable number of parameters to be passed in.  The type of the parameter is a lambda expression that has no parameters and returns an object.  This works well for passing in arguments from the calling method.

The helper method iterates through each lambda expression, and for each expression it compiles it and executes it.  If it evaluates to null, an ArgumentNullException is thrown.  We want to pass in the name of the argument into ArgumentNullException’s constructor, so to do this we need to decompose the lambda expression.

The expression’s body is actually a member expression, so we cast to that, get the Member object, access its Name property, and finally pass this value to the constructor.

Of course there is a nominal performance cost with this approach (nothing is for free), so if your method will be called in a tight loop then it might make sense to just code the null check yourself.

But my performance testing showed the overhead to be very acceptable, and the time spent executing CheckArgumentNull was usually minimal in the context of executing the entire method.

Hope you find this useful.

Just when I gave up hope that I would have to retire a handful of attributes from my source code because they contained sensitive information (e.g. the name of the code reviewer), I came across this little gem in .NET – conditional attributes.

Now those “troublesome” attributes look something like this:

[Conditional("DEBUG")]
[AttributeUsage(AttributeTargets.All)]
public class CodeQualityAttribute : Attribute
{
    public String Author { get; set; }
    public String CodeReviewer { get; set; }
    public String UnitTestCompleted { get; set; }
    public Boolean OptimizationNeeded { get; set; }
}

By applying the Conditional attribute with “DEBUG” in the constructor, an attribute will only be compiled for debug builds — not only when it’s defined, but also when it’s used.

Now I can have the best of both worlds – sensitive information in my debug assemblies (which I can submit to a reflection utility for reporting), and clean release assemblies.

Pretty cool feature, huh?

I recently needed to store data on a per-thread basis.  This was the first time I ever needed to do that and it was a bit of a mind shift for me.   Normally when I used threads I would share data across threads – not isolate data within a thread.

The situation was in a WCF server application where I needed to make the user id associated with the service call available to various business objects called by the service method.  One approach could have been for the service methods to pass the user id into the business objects, but that would have gotten a bit tedious.

Since each service call received by my WCF server was on a different thread (using the thread pool), storing the user id in a place specific to the current thread made the most sense.  Fortunately, this can be done in .NET by using thread local storage (TLS).

My first exposure to TLS was in a .NET book that covered this in the form of named data slots, which is a general mechanism that allows you to store any type of data specific to a thread.

So I started down the path using the static Thread.GetNamedDataSlot and Thread.SetData methods, but I noticed that MSDN recommended another mechanism for TLS – the ThreadStatic attribute.  I’m glad I caught this because the book did not cover it, and data slots are a bit sloppy to work with.

What’s so nice about the ThreadStatic attribute is that it can be applied directly to a static field, so your data is strongly typed and stands on its own (as opposed to being thrown into a general named collection as is done with data slots).  And according to MSDN, ThreadStatic is faster than data slots.

So here’s the code:

public static class SystemGlobals
{
    [ThreadStatic]
    private static Int32 _userId;

    public static Int32 UserId
    {
        get { return _userId; }
        set { _userId = value; }
    }
}

Since the private _userId variable is a static field decorated with the ThreadStatic attribute, its contents are unique per thread.  The public UserId property wraps this value and can be set by the WCF service method (which knows the user id via the service call), and can be easily accessed by any business object that needs it.  For example:

public class MyBusinessObject
{
    public void DoIt()
    {
        if (SystemGlobals.UserId == 123)
            RaiseSalary();
    }
}

This is much cleaner than passing the user id into the business object, and creates a nice isolated thread context for your business objects to run in.

I’m sure data slots have their place in some situations, but the ThreadStatic attribute is faster, safer and easier.

Hope this helps!

Up until recently,  I had been following a pattern in my unit tests of catching expected exceptions that is similar to the following:

[TestMethod()]
public void AddTaskTest()
{
    Schedule target = new Schedule("* * * * *", "Every minute");
    ScheduledTask scheduledTask = null;

    Boolean isCaught = false;
    try
    {
        target.AddTask(scheduledTask);
    }
    catch (ArgumentNullException) { isCaught = true; }
    Assert.IsTrue(isCaught);
}

This works, but is a bit of a pain to write every time you want to check that an exception gets thrown by the method being tested.

I found a better approach at this blog post by Pedro Silva of Microsoft.

I modified it slightly to take a generic type parameter instead of passing in the type as a formal parameter (a little easier in my opinion).

Now the unit test looks like this:

[TestMethod()]
public void AddTaskTest()
{
    Schedule target = new Schedule("* * * * *", "Every minute");
    ScheduledTask scheduledTask = null;

    UnitTestHelper.TestException<ArgumentNullException>(() =>
        target.AddTask(scheduledTask));
}

Much simpler – especially when you’re testing for lots of exceptions!

I’m using a lambda expression in this example, but you can also use an anonymous delegate as in the blog.  I just think lambdas are more succint, but either will do.

Here’s the code with my tweaks (comments removed for brevity – please check the original blog post for more info).

public static class UnitTestHelper
{
    static public void TestException<T>(Action action)
    {
        try
        {
            action();
            Assert.Fail("Test should have thrown exception " +
                typeof(T).Name + ".");
        }
        catch (AssertFailedException) { throw; }
        catch (Exception e)
        {
            Assert.IsInstanceOfType(e, typeof(T),
                "Exception is not of the expected type.", typeof(T).Name);
        }
    }
}

Sometimes it’s desirable to make internal types and members available to other assemblies.  A good example of this is when writing unit tests.

I have to confess that sometimes I would temporarily make a method public so I could more easily unit test it.  Or I would generate a private accessor, but that can be annoying when you refactor code later on.

But aside from unit testing, I never had a good reason to make internals available to other assemblies.  That recently changed when I was coding a serializable type that looks something like this:

[DataContract]
public class SessionResponse
{
    [DataMember]
    public SessionState SessionState { get; internal set; }

    [DataMember]
    public Guid SessionKey { get; internal set; }
}

The SessionState and SessionKey properties are set by the server, so it makes sense for them to be readonly on the client.  The problem is that the code on the server side that sets these properties is in a different assembly from where the serializable type is defined.

This results in a compilation error since the “internal” modifier restricts access to that assembly only.  What we need is to make these assemblies “friends”.  You can read more about friend assemblies on MSDN here.

An assembly can be made a friend of another by marking it with the InternalsVisibleTo assembly attribute.

For example, in the AssemblyInfo.cs file of the assembly that contains the SessionResponse type, I added the following:

[assembly: InternalsVisibleTo("MyServerAssemblyName, PublicKey=0047…")]

My server assembly already had a strong name, so I didn’t have to generate one.  But the problem was obtaining its public key so I could fill in the PublicKey value in the InternalsVisibleTo attribute.

I found a helpful blog entry here that shows how to do it.  You basically need to open up a Visual Studio command prompt, and then use the .NET Strong Name Utility to extract the public key from your strong name key file:

sn.exe -p MyStrongNameKey.snk MyStrongNameKey.PublicKey

sn.exe -tp MyStrongNameKey.PublicKey

Be sure to remove the line breaks from the public key that is displayed in the console before pasting it into the InternalsVisibleTo attribute.

And that’s it!  Now the server assembly can set the SessionState and SessionKey properties, and these properties will be readonly on the client.

Hope this helps.

A mutex (“mutual exclusion”) is a synchronization device used to ensure exclusive access to a system resource.  In a limited sense, a mutex is similar to (although costlier than) the lock keyword in that it can be used to protect state variables that are under contention by multiple threads.

But the mutex has the ability to be used not only across threads, but across processes (hence the additional cost over a mere lock).

The Canonical Mutex Example

The oft-cited mutex example is that of ensuring that an application be run just once.  Here’s the code to do that:

static void Main(string[] args)
{
    Mutex mutex = new Mutex(false, "My killer app");

    if (mutex.WaitOne(3000))
    {
        Console.WriteLine("This application is already running.");
        return;
    }

    try
    {
        RunTheApp();
    }
    finally
    {
        mutex.ReleaseMutex();
    }
}

In this example, we create a named mutex that becomes associated with an operating-system object of the name “My killer app”.  Since the name is system-wide, it is important to give it a globally unique name.  We also specified false in the constructor to indicate that we don’t need to initially own the mutex.

We then wait to acquire the mutex.  If we get it within 3 seconds, we hold onto it and run the app.  If we don’t get it within 3 seconds we give the user a message that somebody else is running the app, and then exit out.

Notice that after acquiring the mutex we purposely don’t release it until the application is finished.  This prevents anyone else on the current machine from getting access to our named mutex (including another instance of our app).

The mutex is ultimately released when the app terminates.  To guarantee this, it’s best to put it in a try/finally block.

This is a nice use for a mutex, but mutexes have other uses, even within a single running process.

Protecting the Neutral Zone

The Neutral Zone was a fictitious buffer zone in Star Trek that separated the Federation from the likes of the Romulans and Klingons.  If a ship from either side entered the Neutral Zone, it was usually considered an act of war.  But as long as both sides did not enter at the same time, things could typically be ironed out between both parties to avoid catastrophe.

Assume that we’re writing a Star Trek simulation game in C#.  Let’s protect our Neutral Zone with a mutex.

We will name our mutex “The Neutral Zone”.  As long as the code instantiates a mutex with this name and waits on it, we will properly protect the Neutral Zone and avoid interstellar war.

Our main code might look something like this:

public static void Main()
{
    FederationStarship enterprise = new FederationStarship();
    RomulanWarbird warbird = new RomulanWarbird();

    Thread thread1 = new Thread(enterprise.Explore);
    Thread thread2 = new Thread(warbird.Conquer);

    thread1.Start();
    thread2.Start();

    thread1.Join();
    thread2.Join();

    Console.WriteLine("Press a key to exit...");
    Console.ReadLine();
}

We start by creating an instance of the FederationStarship class, as well as an instance of the RomulanWarbird class.  Next we spin up a thread for each, provide an entry point, start our threads, and wait for our ships to finish their business of exploration or conquering.

The two classes look like this:

public class FederationStarship
{
    public void Explore()
    {
        for (int i = 0; i < 2; i++)
            EnterNeutralZone();
    }

    public void EnterNeutralZone()
    {
        Mutex _mutex = new Mutex(false, "The Neutral Zone");

        Console.WriteLine("{0,2} Enterprise waiting to enter the Neutral Zone", DateTime.Now.ToString("h:mm:ss.fff"));
        _mutex.WaitOne();

        Console.WriteLine("{0,2} Enterprise entering the Neutral Zone", DateTime.Now.ToString("h:mm:ss.fff"));

        // Simulate exploring the Neutral Zone
        Thread.Sleep(300);

        Console.WriteLine("{0,2} Enterprise exiting the Neutral Zone", DateTime.Now.ToString("h:mm:ss.fff"));
        _mutex.ReleaseMutex();
    }
}

public class RomulanWarbird
{
    public void Conquer()
    {
        for (int i = 0; i < 2; i++)
            EnterNeutralZone();
    }

    public void EnterNeutralZone()
    {
        Mutex _mutex = new Mutex(false, "The Neutral Zone");

        Console.WriteLine("{0,2} Warbird waiting to enter the Neutral Zone", DateTime.Now.ToString("h:mm:ss.fff"));
        _mutex.WaitOne();

        Console.WriteLine("{0,2} Warbird entering the Neutral Zone", DateTime.Now.ToString("h:mm:ss.fff"));

        // Simulate some mischief in the Neutral Zone
        Thread.Sleep(500);

        Console.WriteLine("{0,2} Warbird exiting the Neutral Zone", DateTime.Now.ToString("h:mm:ss.fff"));
        _mutex.ReleaseMutex();
    }
}

Running the program produces the following output:

image

Notice that we have successfully prevented both ships from entering the Neutral Zone at the same time.  If a ship tries to enter and another ship is already inside, it will wait until it leaves.  This is because of the mutex and our consistent usage of it in both the FederationStarship and RomulanWarbird classes.

If one of the ships decided not to use it, then they could have entered the Neutral Zone without regard to the other ship’s presence.  The Romulans might be able to pull this off with their cloaking device, but for the sake of argument let’s just say that today they are following protocol and decide to use our mutex.

Design Thoughts

As I mentioned earlier, synchronizing with a mutex is a bit costlier than synchronizing with a lock (on the order of milliseconds as opposed to nanoseconds).  So why use it within a single application?

We certainly wouldn’t use a mutex to simply protect an instance field from multiple threads.  A lock would do fine and would be very fast.

I suppose we could have created a static class that encapsulated a public synchronization object, and both ship classes could have locked around that.  Or we could have shared a local mutex (i.e. non-named) between the classes in some fashion and not have resorted to the heavier named mutex (which associates the mutex with an operating system object of that name).

These are definitely some avenues to consider.  The advantage of the named mutex is that it is easily referenced by classes that know nothing about each other.  You simply instantiate a new mutex of that same name, and don’t have to worry about sharing an existing mutex instance between decoupled classes.

And if you need to protect a resource across processes, the named mutex is the way to go.

Hope this was useful reading, and help keep the Neutral Zone safe!  :-)

I was going to wait until I got 1000 hits on my blog, but then I thought it might be more nostalgic to take a screenshot while it was still in triple digits.  So here it is:

Almost1000

Next stop 1000, and thanks for reading!!  :-)

I have found that developers (including myself) typically write code to be thread-safe only when needed, as opposed to proactively making code thread-safe.  This is understood because writing thread-safe code is not always easy, especially when dealing with instance members.  Just look at the MSDN documention, and you’ll find the following disclaimer under most classes in the Thread Safety section:

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

But once code has been written to be thread-safe, it’s often not very well documented as such.  When the code is revisited months (or even years) later, it’s not immediately evident if the code is thread-safe, or what measures were taken to make it thread-safe.

Taking a cue from a book I recently read on concurrency (Java Concurrency in Practice — see my blog post as well), I have created a few attributes that can be used to decorate your code to help document thread safety.

Attributes can be very helpful with documentation because they help enforce consistency, and can also be read programatically.  For example, we could write a utility that uses reflection to display all classes in an assembly that have been marked as thread-safe.

Before I insert the code that defines the attributes, I’ll give a quick example showing how they might be used.

I recently wrote a file synchronization utility that syncs up files across the public Internet.  Client machines periodically take snapshots of the folders under sync management and send them to the server, at which time the server compares these with its own recent snapshot.  In order to reduce I/O requirements on the server, snapshots of the server’s source folder are taken periodically via a timer and cached.  The timer fires on a thread from the thread pool, and the service calls are processed (via WCF) on threads from the thread pool as well.  Therefore, there’s definitely some concurrency going on, and the code needs to be thread safe.

The following is an excerpt from the File Sync Snapshot Manager class:

[ThreadSafe]
public class FileSyncSnapshotMgr
{
    // ...

    [Guards("_lastSnapshot, _lastDiff")]
    private Object _syncObj = new Object();

    [GuardedBy("_syncObj")]
    private FileSyncSnapshot _lastSnapshot;

    /// <summary>
    /// Gets the last snapshot stored in cache.
    /// </summary>
    public FileSyncSnapshot LastSnapshot
    {
        get { lock (_syncObj) return _lastSnapshot; }
    }

    [GuardedBy("_syncObj")]
    private FileSyncDiff _lastDiff;

    /// <summary>
    /// Gets the last snapshot diff stored in cache.
    /// </summary>
    public FileSyncDiff LastDiff
    {
        get { lock (_syncObj) return _lastDiff; }
    }

    // ...
}

Looking at the code, we see a few things.  The class is marked as thread-safe with the ThreadSafe attribute.  This is just an attribute for documentation purposes and doesn’t have any effect on the code.  But it tells us that someone marked the class as thread-safe, so we assume (or at least hope!) that the class is indeed thread-safe for its intended use.

We can also tell, by looking at the Guards attribute, that our _syncObject field guards the _lastSnapshot and _lastDiff fields.  Conversely, by looking at the GuardedBy attribute, we can quickly identify the sync object that guards a field.

In the case where a field is both the synchronization object and the object it guards, I use the text “self” to designate this.  For example:

[GuardedBy("self")]
private Queue<PackageCreationRequest> _packageCreationRequests =
    new Queue<PackageCreationRequest>();

None of this is very complicated, but I have found that some simple documentation can go a long way.  The hope is that when you (or another developer) revisits the code, that it will be easier to understand the intention behind what was done to make the code thread-safe.

The following is the code that defines the attributes.  Hope this helps.

/// <summary>
/// Represents an attribute that marks a class as thread-safe.
/// This is only for documentation purposes and does not
/// have any affect on the code's actual thread-safety.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class ThreadSafeAttribute : Attribute
{
}

/// <summary>
/// Represents an attribute that marks a class as not being thread-safe.
/// This is only for documentation purposes and does not
/// have any affect on the code's actual thread-safety.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class ThreadUnsafeAttribute : Attribute
{
}

/// <summary>
/// Indicates the synchronization object that guards this item.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class GuardedByAttribute : Attribute
{
    /// <summary>
    /// Initializes a new <see cref="GuardedByAttribute"/> object
    /// and sets the <see cref="SyncObjectName"/> property.
    /// </summary>
    /// <param name="syncObjectName">The name of the sync object.</param>
    public GuardedByAttribute(String syncObjectName)
    {
        SyncObjectName = syncObjectName;
    }

    /// <summary>
    /// Gets or sets the name of the synchronization object that guards this item.
    /// </summary>
    public String SyncObjectName { get; set; }
}

/// <summary>
/// Indicates the items that this synchronization object guards.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class GuardsAttribute : Attribute
{
    /// <summary>
    /// Initializes a new <see cref="GuardsAttribute"/> object
    /// and sets the <see cref="Items"/> property.
    /// </summary>
    /// <param name="syncObjectName">The name of the sync object.</param>
    public GuardsAttribute(String items)
    {
        Items = items;
    }

    /// <summary>
    /// Gets or sets a comma-separated list of items guarded by this synchronization object.
    /// </summary>
    public String Items { get; set; }
}

I just came across a free online book about threading in C# on www.albahari.com.  The main page is here and you can download the entire PDF here.

The online book is a bit different from Chapter 19 (Threading) from the book C# 3.0 in a Nutshell, although I’m not sure if this was written before or after the book.

The topic of threading is broken down into four sections in the online book:

  • Getting Started (overview and concepts)
  • Basic Synchronization (e.g. locking, thread safety, and wait handles)
  • Using Threads (e.g. thread pooling, and timers)
  • Advanced Topics (e.g. non-blocking synchronization, and wait and pulse)

Lots of good threading examples and discussions, and well worth checking out.

I’m currently writing a test utility to simulate multiple clients hitting a server.  There’s a simple UI that shows what’s going on, but the interesting and useful part are the client objects all running side-by-side without interfering with each other.

This is accomplished by running each client in its own application domain.  When the user initiates a client action from the UI, remoting is used to communicate with the client object in the appropriate app domain.

Everything was working great, and I was pleased with my simulator.  It’s certainly easier to run (and debug!) 10 simulators in a single test utility than having to fire up 10 separate instances of the utility app.

However, after a few minutes when I again initiated a client action from my UI, I got the following dreadful error:

RemotingException

After staring at this for a few seconds, I recalled reading the chapter on app domains in the book C# 3.0 in a Nutshell.  The problem is that remoting objects are leased, and if a leasing interval is left unspecified, the .NET runtime drops the object after about 5 minutes.

One solution is to have your remoting object (i.e. the object that descends from MarshalByRefObject) override the InitializeLifetimeService method and return null.  This tells the CLR to keep the object around for as long as the consumer needs it.

Here’s what the code looks like:

public class MyTestClient : MarshalByRefObject, IMyTestClient
{
    public override object InitializeLifetimeService()
    {
        // Tell the runtime to keep the object around
        return null;
    }
    // etc.

There are other ways to better control the object’s lease, but for my purposes this works great since the consumer of the remoting objects are in the default app domain and are alive for the duration of the utility.

I’m sure there are better discussions of this on MSDN and blogs, but if you encounter the above error, this is one way to solve it.

Hope this helps.

Next Page »