因在執行緒中會有好幾個地方會呼叫TB_keyvalue方法,在呼叫的過程中,會變更TextBox1的值,此時會發生跨執行緒作業無效的問題;我修改了上方參考資料連結的程式碼,如下...
Private Delegate Sub UpdateUICB(ByVal TB1 As System.Windows.Forms.TextBox, ByVal str_ivalue As String, ByVal add_dt As Integer) Sub TB_keyvalue(ByVal TB1 As System.Windows.Forms.TextBox, ByVal str_ivalue As String, Optional ByVal add_dt As Integer = 1) Dim str_dtime As String = String.Empty If add_dt = 1 Then str_dtime = "[" & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & "] " End If If Me.InvokeRequired() Then '你可以想像成,將TB_keyvalue方法指定給UpdateUICB Dim cb As New UpdateUICB(AddressOf TB_keyvalue) '當跑到Invoke時,你可以想像成程式碼去呼叫UpdateUICB,並把參數傳給它,此時就等於程式碼又去呼叫TB_keyvalue方法 Me.Invoke(cb, TB1, str_dtime & str_ivalue, add_dt) Else If TB1.Text = "" Then TB1.Text = str_dtime & str_ivalue Else TB1.Text = str_dtime & str_ivalue & vbCrLf & TB1.Text End If End If End Sub
P.S 我直接把我的想法寫在註解中,如有錯誤請指正,或想幫忙補充的,歡迎留言補充,謝謝。
沒有留言:
張貼留言