我有一個問題,一個非常簡單的代碼跨線程操作無效
Dim temperature As String = SerialPort1.ReadLine.ToString
If temperature.StartsWith("temp") Then
templab.Text = temperature.Substring(4, 2) & "°C"
End If
,它給
Cross-thread operation not valid: Control 'templab' accessed from a thread other than the thread it was created on.
上設置標籤的文本
我在網上搜索對於這一點,我發現了一些解決方案,但我的問題不是這樣的,我已經用Visual Studio 2008和Windows 7編寫了相同的代碼,它沒有給我任何錯誤。現在我使用Windows 8和Visual Studio 2012.我怎樣才能解決這個問題,而無需調用?在此先感謝
全碼:
Public Class Form1
Private Sub SerialPort1_DataReceived(sender As Object, e As IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim temperature As String = SerialPort1.ReadLine.ToString
If temperature.StartsWith("temp") Then
templab.Text = temperature.Substring(4, 2) & "°C"
End If
' My.Computer.Audio.Play("C:\Users\Chris\Desktop\ROMANTIC MUSIC INSTRUMENTAL, PIANO AND SAXOPHONE.wav", AudioPlayMode.Background)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SerialPort1.Open()
End Sub
End Class
上面的代碼給出了t他錯誤,因爲它從與運行templab文本框的UI線程不同的線程訪問UI元素(templab)。你能顯示包含這部分的完整代碼嗎? – Steve 2013-04-20 20:29:34
所以我怎麼能創建標籤在同一個線程的代碼? – 2013-04-20 20:30:35
注意:如果你創建另一個線程控制,主UI線程將當它試圖畫你的形式做一個跨線程調用...... – DarkSquirrel42 2013-04-20 20:33:31