I'm having trouble using threading in a VB.net application I'm writing. I have a really simple version here to illustrate the problem I'm having.
It works perfectly if I load my form and have the VNC control connect to my VNC server as a single thread application using this code:
Imports VncSharp
Imports System.Windows.Forms
Imports System.ComponentModel
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not RemoteDesktop1.IsConnected Then
Dim Host As String = "10.0.0.1"
RemoteDesktop1.Connect(Host)
End If
End Sub
End Class
In order to make the connection occur in the background, this is the code I've tried using the backgroundworker control. I followed the information in this article to handle referencing the controls on the form using an instance, but I still get an error when it tries to use the VNCSharp control (RemoteDesktop1) to connect to a VNC server at the line: Instance.RemoteDesktop1.Connect(Host)
The error is:
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'RemoteDesktop1' accessed from a thread other than the thread it was created on.'
Here's the code:
Imports VncSharp
Imports System.Windows.Forms
Imports System.ComponentModel
Public Class Form1
'Taken from https://stackoverflow.com/questions/29422339/update-control-on-main-form-via-background-worker-with-method-in-another-class-v
Private Shared _instance As Form1
Public ReadOnly Property Instance As Form1
Get
Return _instance
End Get
End Property
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
_instance = Me
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
System.Threading.Thread.Sleep(1000)
If Not Instance.RemoteDesktop1.IsConnected Then
Dim Host As String = "10.0.0.1"
Instance.RemoteDesktop1.Connect(Host)
'Connect()
End If
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("BG1 complete")
End Sub
End Class