Mike Volodarsky's blog

Formerly the core server PM for IIS 7.0 and ASP.NET, now I run LeanSentry.
UPDATES: New troubleshooting guide released! Fix IIS website hangs →

Be a part of the energy revolution / Help Save Kilowatt Ours

I dont usually post activist stuff on the blog, but I have to make an exception in this case.

A year ago, I caught a late night showing of Jeff Barrie's Killowatt Ours, a 1 hour long film about the true impact of energy production on our environment, our health, and the extent to which we can help meet our growing energy demands by simply reducing our energy footprint.

Lets just say the film was eye-opening, even given the fact that I've been in the energy field in one way or another for some time. 

Did you know that coal energy plants have contributed to the largest incidence of child astma in history, severe smog pollution in our nations parks, and the mercury poisoning of the majority of state bodies of water?

Did you also know that the state of california, and others have succesfully replaced the need to build new power plants by implementing simple power conservation measures, or the "conversation power plant"? 

The video also shares the simple steps you can take today in your home to slash your power bill by thousands, all the while helping us become energy indepdendent and slow the damage to our environment.

Now, you can watch the entire video with convinent chapter segments at http://www.kilowattours.org/script.php.

Killowatt Ours

If you are interested in energy conservation, or havent had the time to read about the facts, this video is all you need. 

Also, be sure to help save Killowatt Ours, which has been helping champion energy consevation in the US, by making a donation. With a 29.95 donation, you get the T-shirt :) .

 

Regards,

Mike

Fun with file locking

If you are developing code that uses distributed synchronization or messaging, you sometimes might need to use files as a locking mechanism.  This can be useful because files are persistent (beyond thread, process, or even power session lifetime), and access to them is synchronized between multiple processes if you select the proper file access and sharing modes. 

C# example of taking a file lock:

using (FileStream lockFile = new FileStream(

            lockPath,

            FileMode.OpenOrCreate,

            FileAccess.ReadWrite,

            FileShare.Delete

       ))

{

    // 1. Read lock information from file

    // 2. If not locked, write the lock information

}

If multiple threads or processes are accessing this lock file, the first process to open the file will lock it, blocking others from accessing it (more on why FileShare.Delete and not  FileShare.None in a moment).

This provides the synchronization necessary for safe concurrent access of the file lock.  Clients using the code should try to open the file in a try/catch loop, until a certain timeout is reached, to provide the blocking behavior for the file lock.

Where it gets a bit more interesting is when you are done with the lock, and want to release it.  

A good way to do this is to delete the file (you could also write the file to indicate that you no longer hold the lock, but who wants to have left over lock files?).

Naturally, you’ll want to first open the file with the same exclusive access as you did when locking it, to insure that you are still the one that holds the lock.  Unfortunately, it turns out that there isn’t a way to delete the file using the file handle that you have already opened.  You have to use the File.Delete(string path) API which calls WIN32 DeleteFile() and re-opens the file in order to delete it, or re-open the file with FileOptions.DeleteOnClose (FILE_FLAG_DELETE_ON_CLOSE).  This is where you get into trouble because you already have the file open under a lock to prevent other writers from taking it.

This is where our FileShare.Delete (FILE_SHARE_DELETE) comes in.  By opening the file with this flag, we are prohibiting any lock taking operations from being performed, but allowing the file to be deleted by someone else.

C# example of releasing the file lock:

using (FileStream lockFile = new FileStream(

            lockPath,

            FileMode.OpenOrCreate,

            FileAccess.ReadWrite,

            FileShare.Delete

       ))

{

    // 1. Read lock information from file

 

    // 2. If locked by us, delete the file:

    File.Delete(lockPath);

}

The file will be deleted as soon as our handle to the file is closed at the end of the using {} scope.

Note that this example is meant as a mechanism for cooperative persistent file locking between multiple threads or processes.  It is not meant as a way to guard against malicious or misbehaving code that wants to access the file, because anyone can break the rules while the file is not locked.

The benefit of this approach is that you can create persistent file locks that do not necessarily go away when an owning process terminates, and do not require you to keep the file exclusively locked for the duration of the lock.  You can also provide lock override or timeout semantics on top of this mechanism that would not be possible with an exclusive lock approach.

You can also download the example file lock library and source code (as is, no guarantees, no limitations on use).

Using this library you can create file locks like this:

using (FileLock l = new FileLock(path, lockId, “mylock”))

{

    // do stuff under the file lock …

} // lock automatically released here

Of course, there are other ways to do inter-process locking on Windows, including global mutexes, that may be more appropriate depending on the situation.

If you work with the file system often, be sure to check out the CreateFile documentation: http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx.  CreateFile is really the swiss army knife of Windows - having a good understanding of the access modes, sharing modes, and file flags can unlock a number of useful possibilities for your code. 

Best,

 

Mike