仅在使用断点时对象同步异常,在 F# 中

Object synchronization exception only when using breakpoints, in F#

我收到这个错误:

Unhandled exception. System.Threading.SynchronizationLockException: Object synchronization method was called from an unsynchronized block of code.
   at System.Threading.Monitor.Exit(Object obj)

使用此代码:

        this.UpdateTimer <-
            let interval = TimeSpan.FromSeconds(0.5)
            new Timer(TimerCallback(fun x ->
                (
                    try
                        if Monitor.TryEnter(UpdateLock) then
                            try
                                let response = RestClient.Execute(Request)
                                response |> ignore
                            with ex ->
                                Logging.Error(printfn "%s" ex.Message)
                    finally
                        Monitor.Exit(UpdateLock)
                )
            ), new Object(), int interval.TotalMilliseconds, int interval.TotalMilliseconds)

但是当我在 RestClient.Execute 调用上设置断点时, 会发生这种情况。 RestClient 是 RestSharp,因为这不是异步调用,所以来自计时器的调用应该保持在同一个线程上。

代码有明显问题吗?或者它可能是调试器问题,它在另一个线程上恢复执行?

当您尝试退出您从未进入的锁定对象时会抛出此错误。

当您明确输入Monitor.TryEnter(UpdateLock)时,您必须写Monitor.Exit(UpdateLock)

当你把出口变成 if 这样的时候就可以实现:

if Monitor.TryEnter(UpdateLock) then
    try
        try
            let response = RestClient.Execute(Request)
                response |> ignore
        with ex ->
            Logging.Error(printfn "%s" ex.Message)
    finally
        Monitor.Exit(UpdateLock)

希望对您有所帮助。