Object synchronization method was called from an unsynchronized block of code

Delphi 11.3

VB.Net plugin module.

The Host delphi application is not threaded. I am able to create load the module and create the visual plugin The dll is implementing a 3rd party .net visual assembly. It is all working at the start. However, I try to call a function on the 3rd party assembly after it is loaded I get the “Object synchronization method was called from an unsynchronized block of code.” I tried wrapping the function in a Invokerequired. It executes the

Public Sub OpenDocument2(documentID As String, token As String) Implements ISpeechKitDictationPlugin.OpenDocument2


'TheModuleController.RaiseLog("Opening dictation document and synchronizing VuiController." & documentID & " " & token)
If Not fDocumentOpen Then

    If Me.InvokeRequired Then
        ' Called from background thread → marshal to UI thread
        Me.BeginInvoke(Sub()
                           Try
                               myVuiController.Open(Panel1, documentID, token)
                               myVuiController.Focused = True
                               fDocumentOpen = True
                           Catch ex As Exception
                               TheModuleController.RaiseLog("Error opening VuiController (marshaled): " & ex.Message)
                           End Try
                       End Sub)
    Else
        ' Already on UI thread → safe to call directly
        Try
            myVuiController.Open(Panel1, documentID, token)
            myVuiController.Focused = True
            fDocumentOpen = True
        Catch ex As Exception
            TheModuleController.RaiseLog("Error opening VuiController: " & ex.Message)
        End Try
    End If

End If
'myVuiController.Synchronize()
'TheModuleController.RaiseLog("Done Opening dictation document and synchronizing VuiController.")


End Sub

I have added CoInitializeEx(nil, COINIT_APARTMENTTHREADED); to my delphi application.

When I check the state inside the plugin, (Thread.CurrentThread.GetApartmentState().ToString()) it reports that it is STA. Yet I still get the object synchronization error in the code.

Are there any Hydra options that I can force the winforms to STA that I might be missing?

.

Hi,

You can use standard STAThread attribute.


according to https://stackoverflow.com/questions/9017521/object-synchronization-method-was-called-from-an-unsynchronized-block-of-code-e

Another reason why this exception may occur:

if (Monitor.TryEnter(_lock))
{
    try
    {
        ... await MyMethodAsync(); ...
    }
    finally
    {
        Monitor.Exit(_lock);
    }
}

I get this exception on Monitor.Exit when after ‘await’ another thread continues execution.