C#, Can I check on a lock without trying to acquire it?

Posted by Biff MaGriff on Stack Overflow See other posts from Stack Overflow or by Biff MaGriff
Published on 2011-02-11T22:30:15Z Indexed on 2011/02/11 23:25 UTC
Read the original article Hit count: 244

Filed under:
|
|

Hello,

I have a lock in my c# web app that prevents users from running the update script once it has started.

I was thinking I would put a notification in my master page to let the user know that the data isn't all there yet.

Currently I do my locking like so.

protected void butRefreshData_Click(object sender, EventArgs e)
{
    Thread t = new Thread(new ParameterizedThreadStart(UpdateDatabase));
    t.Start(this);
    //sleep for a bit to ensure that javascript has a chance to get rendered
    Thread.Sleep(100);
}


public static void UpdateDatabase(object con)
{
    if (Monitor.TryEnter(myLock))
    {
        Updater.RepopulateDatabase();
        Monitor.Exit(myLock);
    }
    else
    {
        Common.RegisterStartupScript(con, AlreadyLockedJavaScript);
    }
}

And I do not want to do

if(Monitor.TryEnter(myLock))
    Monitor.Exit(myLock);
else
    //show processing labal

As I imagine there is a slight possibility that it might display the notification when it isn't actually running.

Is there an alternative I can use?

Edit:
Hi Everyone, thanks a lot for your suggestions! Unfortunately I couldn't quite get them to work... However I combined the ideas on 2 answers and came up with my own solution.

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading