Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid a SynchronizationLockException?

I have the following code, which I based off of the Monitor class example on the msdn website.

    private void WebRefresh_Click(object sender, EventArgs e)
    {
    if (WebRefresh.Enabled)//Only call from button
    {
        if (System.Threading.Monitor.TryEnter(deployIsRunning))
        {

                refreshWebVersion();

                System.Threading.Monitor.Exit(deployIsRunning);
        }
    }
    else
    {
        MessageBox.Show("You cannot refresh during a deploy");
    }
}

The code throws SynchronizationLockException on the Monitor.Exit() Call with an error message: "Object synchronization method was called from an unsynchronized block of code." The error's explanation is that I tried to release a mutex that I did not own, but I can not enter the block of code where Exit is called unless TryEnter is successful. How do I remove this error?

like image 415
amccormack Avatar asked Feb 26 '23 08:02

amccormack


1 Answers

My guess is that deployIsRunning is a variable of type bool or some other value type. Your calls to TryEnter and Exit will box the value, creating a new object every time.

Basically, only ever use a reference type variable for a lock.

like image 90
Jon Skeet Avatar answered Mar 08 '23 07:03

Jon Skeet