vb - MTA exception when displaying a new form from a background worker

-1

I've got a backgroundworker which is fired off from a timer to query an API for new database records.

in the event that a new relevant record is returned, the backgroundworker tries to call a 'DisplayData' function...

    Private Sub BackgroundWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker.DoWork
    Dim api_response As String = API_Check()
      if not api_response = nothing then
        DisplayData(response)
      end if
    End Sub

The DisplayData function looks like this...

 Public Function DisplayData(ByVal Body As String)
    Try
        Dim render_timer As Stopwatch = Stopwatch.StartNew
        Dim Display As New API_Data_Display
        Display.Width = JObject.Parse(Body).SelectToken("WindowSize.Width")
        Display.Height = JObject.Parse(Body).SelectToken("WindowSize.Height")
        Display.TopMost = JObject.Parse(Body).SelectToken("TopMost")
        Display.WebView1.NavigateToString(JObject.Parse(Body).SelectToken("Body"))
        Display.Show()
        render_timer.Stop()
        Console.WriteLine(render_timer.ElapsedMilliseconds & " ms")
 Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try
 End Function

If i perform the API check manually from a button, it works fine and everything goes to plan. The problem is when the backgroundworker runs the API check; I get an exception like so...

System.Runtime.InteropServices.COMException (0x8000001D): Activating a single-threaded class from MTA is not supported (Exception from HRESULT: 0x8000001D)

I've googled the pants out of this and found bits of info about doing my own marshalling, which seems a little drastic. There was also a C# exaple of a workaround here which suggests I can call back to the UI thread before opening the new window, but I'm not sure how to go about doing that.

Has anyone been in this situation before and overcome it without doing your own marshalling?

As always, any help greatly appriciated!

vb.net
backgroundworker
mta
asked on Stack Overflow Oct 18, 2020 by John

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0