LP on .NET

July 30, 2009

Excellent Book on Java Concurrency

Filed under: .NET,C#,Software Development — Larry Parker @ 9:27 pm

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#.

July 7, 2009

Using Timers Instead of Managed Threads

Filed under: .NET,C#,Software Development — Larry Parker @ 9:55 pm

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!

Visual Studio 2008 Unit Testing Bug

Filed under: .NET,C#,Visual Studio,VSTS — Larry Parker @ 11:47 am

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.

July 2, 2009

System.Threading.Thread Constructors Tip

Filed under: .NET,C#,Software Development,Visual Studio — Larry Parker @ 11:48 am

Just a quick tip when calling any of the constructors for System.Threading.Thread.  Many examples (including the MSDN documentation) explicitly create a ThreadStart (or ParameterizedThreadStart) instance and pass that into the constructor:

void DoIt()
{
    Thread thread = new Thread(new ThreadStart(DoWork));
    thread.Start();
}

void DoWork()
{
}

This is of course totally fine, but you can save a couple of keystrokes by just passing in the method name itself:

void DoIt()
{
    Thread thread = new Thread(DoWork);
    thread.Start();
}

This compiles to the exact same IL code (you can see this for yourself using Reflector or some other utility).

I just find it a bit easier than instantiating an object, and the code is easier to read as well.

Hope this helps!

Create a free website or blog at WordPress.com.