HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Waiting for a lock to release with Thread.Sleep()?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
waitingwithsleepreleaseforthreadlock

Problem

There's a follow-up: Waiting for a lock to release with ManualResetEvent and Quartz.

I've written a simple Lock-Mechanism which is saving the states of the locks in a database. Now I need to wait for a Lock to release or timeout after a certain amount of time (blocking the main thread, this is intentional). My implementation is looking like this:

/// Waits for the lock to be released within the given timeout.
/// The name of the lock.
/// The timeout in seconds.
/// True if the Lock was released.
public bool waitForLock(String lockName, Int32 timeout)
{
    // IsLocked(String) does query the database for the status
    while(locker.IsLocked(lockName) && timeout > 0)
    {
        Threading.Thread.Sleep(1000);
        timeout--;
    }

    return !locker.IsLocked(lockName);
}


I always get a little bit itchy if I have to use Thread.Sleep, but I'm not sure why.

Is something wrong with this design/approach and will it bite me later? Or is there a better way to handle this?

Edit: Further clarifications: I have full control over the locker and anything affiliated with it. The main intention for this is to make sure that certain operations will not overlap, each of these operations should be taking well less then 5 seconds. The load on the server is not really an issue, because the realistic maximum number of clients simultaneous waiting for a lock could be 10 (in my case).

The blocking of the thread is not as intentional is I have stated. The best thing would be if I could keep the message pumping still active, but I fail to see how I can achieve that goal in combination with polling the database (and without the need to introduce a timer with a callback).

Edit2: The locked part is not the database, the database is only holding the status of the locks. I'm using this locking system to make sure that no operation protected by this can execute at the same time on different client machines.

Solution

An easier answer might be to use a ManualResetEvent. You can block the current thread for a timeout period until another thread signals the ManualResetEvent.

http://philiprieck.com/blog/archive/2004/01/27/WaitHandleSample.aspx

http://www.yoda.arachsys.com/csharp/threads/waithandles.shtml

Basically, blocking thread calls mre.Wait(), processing thread works until it calls mre.Set(). No sleeping, none of this other stuff.

An important note, always Dispose of your ManualResetEvents. Leaking handles is a bad call, this object reaches out into the COM world.

Context

StackExchange Code Review Q#2650, answer score: 12

Revisions (0)

No revisions yet.