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

时间:2019-11-19 04:11:43

标签: f# thread-synchronization

我收到此错误:

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,因为它不是异步调用,因此来自计时器的调用应保留在同一线程上。

代码是否存在明显问题?还是一个调试器问题,它在另一个线程上恢复执行?

1 个答案:

答案 0 :(得分:1)

当您尝试退出从未输入的锁对象时,将引发此错误。

确定输入Monitor.Exit(UpdateLock)时,您必须写Monitor.TryEnter(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)

我希望这会有所帮助。