Getting cross thread Error even Used Invoke

318 views Asked by At

Getting cross thread error when executing tcViewer.TabPages.Add(t) statement.

Code is as below.

Private Function fff(t As TabPage)
    tcViewer.TabPages.Add(t)   'giving cross thread error
End Function

Function WebBrowserThread()
    Dim t As TabPage = New TabPage((k + 1).ToString())
    t.Name = k.ToString()
    tcViewer.Invoke(fff(t))
End Function

Please guide.

2

There are 2 answers

0
Damien_The_Unbeliever On

I think you should move the creation of the new TabPage onto the UI thread as well:

Private Function fff(k as Integer)
    Dim t As TabPage = New TabPage((k + 1).ToString())
    t.Name = k.ToString()
    tcViewer.TabPages.Add(t)
End Function

Function WebBrowserThread()
    tcViewer.Invoke(fff(k))
End Function

When you construct the TabPage, you eventually reach this call stack:

System.Windows.Forms.dll!System.Windows.Forms.Control.CreateHandle()
System.Windows.Forms.dll!System.Windows.Forms.Application.MarshalingControl.MarshalingControl()
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.MarshalingControl.get()
System.Windows.Forms.dll!System.Windows.Forms.WindowsFormsSynchronizationContext.WindowsFormsSynchronizationContext()
System.Windows.Forms.dll!System.Windows.Forms.WindowsFormsSynchronizationContext.InstallIfNeeded()
System.Windows.Forms.dll!System.Windows.Forms.Control.Control(bool autoInstallSyncContext)
System.Windows.Forms.dll!System.Windows.Forms.ScrollableControl.ScrollableControl()
System.Windows.Forms.dll!System.Windows.Forms.Panel.Panel()
System.Windows.Forms.dll!System.Windows.Forms.TabPage.TabPage()
System.Windows.Forms.dll!System.Windows.Forms.TabPage.TabPage(string text) 

At this point, the Handle is being created, and if you're doing that on the wrong thread, everything else is going to start going wrong (because the thread that the control was created on isn't going to run a message pump)

8
Ahmed Fwela On

i don't know what invoking error you get but i suggest disabling cross-thread checking by adding this in the constructor or loaded event (very helpful when dealing with APIs)

Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False

Check this http://tech.xster.net/tips/invoke-ui-changes-across-threads-on-vb-net/

in wpf such problems are easy to fix because you have a single thread for all the controls (Dispatcher.Invoke)

Update

dealing with the UI controls have to be on the UI thread

Me.Invoke(sub()
            Dim t As TabPage = New TabPage((k + 1).ToString())
            t.Name = k.ToString()
            fff(t)
          End Sub)




  Me.Invoke(sub()
               tcViewer.TabPages.Add(t)
            End Sub)