How to avoid SynchronizationLockException?

I have the following code that I based on 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 a SynchronizationLockException in a call to Monitor.Exit () with the error message: "The object synchronization method was called from an unsynchronized code block." The explanation for the error is that I was trying to free a mutex that I did not have, but I cannot enter a block of code where Exit is called if TryEnter not successful. How to remove this error?

+4
source share
1 answer

I assume deployIsRunning is a variable of type bool or some other type of value. Your calls to TryEnter and Exit will contain a value, creating a new object each time.

Basically, only ever use a variable of a reference type to block.

+8
source

Source: https://habr.com/ru/post/1336463/


All Articles