Ziff Davis EnterpriseHeader
Advertisement
Advertisement
Advertisement
Tuesday, January 27, 2009 4:37 PM/EST

The C# lock statement

(Follow me on twitter where I give out software development tips throughout the day: http://twitter.com/jeffcogswell )
(Check out my other blog: http://programmingbootcamp.blogspot.com/ )

Here's something that's vital to understanding with ASP.NET programming. Whenever you're programming for ASP.NET, you need to understand that you're writing multi-threaded code. If multiple people are using your site simultaneously, then each session normally gets a separate thread in the same process.

If you're doing something such as modifying a file, you can run into some problems if two threads try to access the file at the same time. That's where the lock statement comes in handy. The lock statement lets you specify a block of code that only one thread can run at a time. Imagine a narrow bridge that's strong enough to hold only one person at a time. If there's a line of people waiting to use the bridge, the next person can't enter the bridge until the person on it gets across. So it works with a block of code guarded by a lock statement.

Easy enough. But to use a lock statement, you need to allocate an object to go alongside the lock. The reason for this object is you can actually declare more than one block of code and only one thread can be in any of these blocks at a given time.

Here's a quick and dirty example.

static Object FileLockObj = new Object();
void WriteToFile(string sometext) {
    lock (FileLockObj) {
        System.IO.File.AppendAllText("c:\\temp\\log.log", sometext);
    }
}

The AppendAllText line can only run one thread at a time. If multiple threads call the function simultaneously, they'll have to wait in line as only one thread can go inside the lock block at a time. When the current thread inside finishes, the next one gets to go in. That way, you won't have more than one thread trying to write to the file simultaneously.

If you're doing a lot of work with files, however, including reading and writing, .NET also includes a set of locks specifically for files. The idea behind these locks is that multiple threads should be able to read a file at any given time. But if a thread needs to write to a file (i.e. modify it), then that thread alone should have access to the file during the write. That's how the ReaderWriterLock class works. If you're interested in learning about that, you're in luck! I wrote an article here on DevSource a little over a year ago. You can find the article here. Enjoy!

TrackBack

TrackBack

http://blogs.devsource.com/cgi-bin/mte/mt-tb.cgi/16328

Post a Comment

 
 
Advertisement

Syndication

Subscribe: