简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM