开发者

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 bloc开发者_Python百科k 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜