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.

I recently ran into that darn Visual Studio bug that I got a few weeks ago:

API restriction: The assembly ‘file:///C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll’ has already loaded from a different location. It cannot be loaded from a new location within the same appdomain

Of course I couldn’t remember what the fix was.  Fortunately I blogged about it and found the answer here (the fix once again was to delete my solution’s user options file).

I guess that’s what technical blogging is all about – keeping a running record of what you encounter in your programming travels.  Let’s hear it for blogging!  :-)

I’m reading an excellent book on concurrency called Java Concurrency in Practice by Brian Goetz.

I’m a .NET / C# developer, so what am I doing reading a book about Java?  Well it turns out that I went to high school with the author, and our paths recently crossed and he was nice enough to give me a signed copy.

The funny thing is that his book covers a subject that I really need to learn more about for my current project at work.  The timing could not have been better.

At first, the Java syntax was a little hard to get past since I’ve never done any Java programming, and have been exclusively reading C# books for the past three years.  But the syntax is very similar to C#, and the library class-names are straightforward enough to get a feel for what they do.

But aside from these subtle language differences, the concepts are totally applicable to C# (and probably most languages), and I’m finding this to be a very useful text on concurrency.

I was reading more of it tonight and came across four topics that I encountered while writing some code at work today that needed to be thread safe.

This is a very thorough book that offers simple examples that demonstrate specific concepts.  I highly recommend it if you need to deal with concurrency issues in your application, whether you program in Java or C#.

I have written several Windows services in .NET over the years, and they have all required some sort of housekeeping to occur in the background (e.g. archive or back up files every hour).

The approach I have used was to create a worker thread that sleeps and iterates until the desired time interval has elapsed.  For example:

public class Housekeeping
{
    public Housekeeping()
    {
        _thread = new Thread(HousekeepingThread);
    }

    private bool _active;
    private Thread _thread;

    public void Start()
    {
        _active = true;
        _thread.Start();
    }

    public void Stop()
    {
        _active = false;
        _thread.Join();
    }

    private void HousekeepingThread()
    {
        int iterations = 0;
        while (_active)
        {
            if (++iterations >= 720)
            {
                DoWork();
                iterations = 0;
            }

            Thread.Sleep(5000);
        }
    }

    private void DoWork()
    {
        // do some work
    }
}

After an hour (720 iterations X 5000 ms = 1 hour), the DoWork method is called and some work is performed.  The thread then resumes sleeping and iterating until the next hour interval elapses.

The reason for sleeping 5 seconds and iterating (instead of simply sleeping for one hour) is to make the thread more manageable.  If the calling program initiates the Stop method, it won’t have to wait more than 5 seconds to abort (although it could be a bit longer if DoWork is called).  This avoids having to abort the thread, which is not very graceful.

This approach is ok, and gives the illusion of some housekeeping occurring “every hour”, but there are a couple of problems with this that I never really considered until I recently read a discussion of timers (in the excellent book C# 3.0 in a Nutshell, by Joseph and Ben Albahari).

In Chapter 19,  Threading, the authors point out the exact technique that I have been using, and its shortcomings.  Nothing like seeing your approach used as an example of what not to do.  :-)

The problem with this pattern (perhaps it’s really an anti-pattern) is that a thread resource is tied up to do nothing but mainly sleep, and the DoWork method will not really be called every hour but will instead slip as time goes on (since DoWork takes some time to perform).

The solution to all of this is to use a timer.  There are several timers in .NET, but for this example we’ll rewrite our Housekeeping class to use System.Threading.Timer:

public class Housekeeping
{
    private Timer _timer;

    public void Start()
    {
        int hourMs = 1000 * 60 * 60;
        _timer = new Timer(DoWork, null, hourMs, hourMs);
    }

    public void Stop()
    {
        _timer.Dispose();
    }

    private void DoWork(Object stateInfo)
    {
        // do some work
    }
}

Not only is this simpler, but you don’t have to create your own thread.  The Timer class will use a thread from the thread pool to execute your callback delegate, so you won’t tie up a thread resource that does nothing but sleep!

Keep in mind that your callback may execute on different threads, so it must be thread safe.

But the best part of the Timer class is that your callback method gets executed on time.  In our example, it will fire exactly after one hour, and then fire exactly every hour thereafter.

Much easier than creating your own thread and managing the time interval yourself!

I just ran into a bit of a nasty bug in Visual Studio 2008 while doing some unit testing.  At some point after a bunch of edit / compile / unit test iterations, I got the following error trying to compile my solution:

API restriction: The assembly ‘file:///C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll’ has already loaded from a different location. It cannot be loaded from a new location within the same appdomain

Restarting Visual Studio did not help.  Neither did cleaning and rebuilding my solution.

I found this thread on the MSDN VSTS forum which discusses the problem.  Microsoft apparently could not reproduce the problem, and closed out a bug report submitted to Microsoft Connect as “Closed (Not Reproducible)”.

If you’re running into this problem, I recommend reading through the entire forum thread, because the solution does not seem to be so cut and dry.

But for me, deleting my solution’s user options file (e.g. MySolution.suo) did the trick.

Hope this helps.

Next Page »