2016-12-14 46 views
0

我有一個表單,它可以從串口捕獲十六進制代碼。我希望一收到十六進制就立即關閉窗體。但我得到一個錯誤,不能關閉DataReceived事件的形式。DataRecieved事件中的關閉窗體

我的代碼:

Public hex As String 
Dim sp As SerialPort 

    Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived 
     Dim t_hex As String = sp.ReadLine() 

     If Len(t_hex) < 21 Then 
      Exit Sub 
     End If 

     t_hex = Mid(t_hex, 11, 11) 

     hex = t_hex 
     sp.Close() 
     Me.Close() '' ERROR LINE 

    End Sub 

錯誤:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll 

Additional information: Cross-thread operation not valid: Control 'Dlg_CardRead' accessed from a thread other than the thread it was created on. 

什麼是接近這個和關閉形式的正確方法是什麼?

感謝

回答

0

找到了答案:

Public hex As String 
Dim sp As SerialPort 

    Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived 
     Dim t_hex As String = sp.ReadLine() 

     If Len(t_hex) < 21 Then 
      Exit Sub 
     End If 

     t_hex = Mid(t_hex, 11, 11) 

     hex = t_hex 
     sp.Close() 
     CloseMe() 

    End Sub 

Private Sub CloseMe() 
    If Me.InvokeRequired Then 
     Me.Invoke(New MethodInvoker(AddressOf CloseMe)) 
     Exit Sub 
    End If 
    Me.Close() 
End Sub 

編輯:

與第一代碼的問題是,我在呼喚從贏方法形成另一個線程內螺紋。換句話說,DataReceived事件在另一個線程中運行,結果我不能在該線程中使用Me.Close()InvokeRequired屬性返回true,如果您在任何線程而不是UI線程,並且Invoke方法從UI線程調用給定的方法。

+1

沒有解釋的答案不是很好的答案恕我直言。你能詳細說明這個問題是什麼以及它如何修復它? – GuidoG

+0

@GuidoG你是對的。編輯我的答案進一步解釋。 – KababChi