System.InvalidOperationException was unhandled

These are my code:

Sub AttemptLogin(ByVal val As String)
        Dim MDBConn As OleDbConnection
        Dim MDBcmd As OleDbCommand
        Dim MDBReader As OleDbDataReader
        Dim ip_check As Integer
        Dim IP_Address As String

            Dim frmConUser As New frmConnectUser
            frmConUser.StartPosition = FormStartPosition.CenterParent
            If val = "REFUSE" Then
                frmConUser.lblAlert.Text = "**The user account is logged on**"
            ElseIf val = "WRONG" Then
                frmConUser.lblAlert.Text = "**The user account is not exsit or the password is not match!**"
            End If
            If frmConUser.txtUserLogin.Text <> "" Then
                MDBConn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Database.mdb;")
                MDBcmd = New OleDbCommand("select * from serverlist order by id", MDBConn)
                MDBReader = MDBcmd.ExecuteReader

                While MDBReader.Read() And ip_check <> 1
                        IP_Address = CStr(MDBReader(1))
                        client = New TcpClient(IP_Address, PORT_NUM)
                        client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)
                        ip_check = 1
                        SendData("CONNECT|" & frmConUser.txtUserLogin.Text & "|" & frmConUser.txtPassword.Text)
                        mnuConnect.Text = "Disconnect"
                        Exit While
                    Catch ex As Exception
                        ip_check = 2
                    End Try
                End While

                If ip_check = 2 Then
                    MsgBox("Server is not active.  Please start server and try again.", MsgBoxStyle.Exclamation, Me.Text)
                    Exit Sub
                End If
            ElseIf mnuConnect.Text = "Disconnect" Then
                mnuConnect.Text = "Connect"
            End If
    End Sub

I have got error msg for "frmConUser.ShowDialog()" when I run twice times:

System.InvalidOperationException was unhandled
  Message="復原作業的內容與套用至對應設定作業的內容不同。可能是因為內容已設定在執行緒上,但沒有還原 (復原)。"
       ÃƒÂ¦Ã‚–¼ System.Threading.SynchronizationContextSwitcher.Undo()
       ÃƒÂ¦Ã‚–¼ System.Threading.ExecutionContextSwitcher.Undo()
       ÃƒÂ¦Ã‚–¼ System.Threading.ExecutionContext.runFinallyCode(Object userData, Boolean exceptionThrown)
       ÃƒÂ¦Ã‚–¼ System.Runtime.CompilerServices.RuntimeHelpers.ExecuteBackoutCodeHelper(Object backoutCode, Object userData, Boolean exceptionThrown)
       ÃƒÂ¦Ã‚–¼ System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       ÃƒÂ¦Ã‚–¼ System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       ÃƒÂ¦Ã‚–¼ System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       ÃƒÂ¦Ã‚–¼ System.Net.ContextAwareResult.Complete(IntPtr userToken)
       ÃƒÂ¦Ã‚–¼ System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
       ÃƒÂ¦Ã‚–¼ System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
       ÃƒÂ¦Ã‚–¼ System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Who is Participating?
gnoonConnect With a Mentor Commented:
I think, you have to call ShowDialog() only in UI-thread. The code below, I add code at top of AttemptLogin to check if current thread is UI thread.
'Declare a delegate for AttemptLogin
Delegate Sub AttemptLoginDelegate(ByVal val As String)
Sub AttemptLogin(ByVal val As String)
  If InvokeRequired Then
    Invoke(New AttemptLoginDelegate(AddressOf AttemptLogin), New Object[]{val})
  End If
End Sub

Open in new window

Try catch that exception and format it with CultureInfo.InvariantCulture, or CultureInfo.GetCulture("en-US"). After that post that exception string (Exception.ToString(culture)) here.
If only one thread call to ShowDialog(), it'll run fine.
I guess it's called from different threads; current thread and thread-pool thread.

Thread-pool thread is automatically lunched after you call client.GetStream.BeginRead(), and the DoRead() will run in the new thread.

I hope you did not call AttemptLogin() from the DoRead(). But you can use Show() instead in multi-threads.
frmConUser.Show(Me) 'Me should be top-level form

Open in new window

KahgusAuthor Commented:
Hi gnoon,
But I need collect some value from frmConUser, and then affect frmMain to run some function.
If I use .show(), how to do that?
Or any solution to handle showdialog() in multithread
KahgusAuthor Commented:
Tank you for your help
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.