0
從調用類中的函數的線程更新文本框不起作用。我試圖讓這個在DLL中工作(但我沒有嘗試)。 DLL正在接受一個對象作爲參數,就像這樣;無法從線程中的類函數更新控件
Sub New(ByVal theObject As Object)
這讓我送的對象,如這一個:
Public Class anObject
Public Sub doSomething()
Form1.TextBox1.Text = "test"
End Sub
End Class
所以我會打電話像這樣的DLL:
Dim theObject As New anObject
Dim theDLL As New SO_TBFromDLL.UpdateTB(theObject)
這之後,DLL將啓動線程,然後稱爲「doSomething」
Public Class UpdateTB
Dim theObjectSet As Object
Sub New(ByVal theObject As Object)
theObjectSet = theObject
'Try to update TB from Thread within current class
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf bghandler)
ctThread.Start()
End Sub
'Try to update TB from Thread within current class
Sub bghandler()
theObjectSet.doSomething()
End Sub
End Class
但這不起作用。我也嘗試使用委託(代碼如下)。
除了這兩個之外,我一直在嘗試其他兩種變體;
從不在Class/DLL中的線程嘗試3。這工作得很好。
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf receiverFunction)
ctThread.Start()
End Sub
隨着receiverFunction
之中:
'Receiver for Thread that's not in DLL (Button 3)
Private Sub receiverFunction()
generaldelegatesN("tb1", "test")
End Sub
嘗試從4線程,這不是在DLL,但使用類內的功能。這也行不通。
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim theObject As New anObjectWithDelegate
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf theObject.doSomething)
ctThread.Start()
End Sub
隨着anObjectWithDelegate
之中:
'Unfortunately, with a delegate it still doesn't work (Button2 & Button4)
Public Class anObjectWithDelegate
Public Sub doSomething()
Form1.generaldelegatesN("tb1", "test")
End Sub
End Class
爲什麼嘗試3個工作,但嘗試4不?這是doSomething()
功能實際上與receiverFunction
隨着加入Form1.
代表團代碼的異常:(如果它的事項)
'The Delegate functions
Delegate Sub generaldelegates(ByVal param1 As String, ByVal param2 As String)
Public generaldelegatesM As generaldelegates
Public Sub generaldelegatesN(ByVal param1 As String, ByVal param2 As String)
'Updates control on main thread:
If Me.InvokeRequired Then
generaldelegatesM = New generaldelegates(AddressOf generaldelegatesN)
Me.BeginInvoke(generaldelegatesM, New Object() {param1, param2})
Else
Select Case param1
Case "tb1"
TextBox1.Text = param2
End Select
End If
End Sub
要回答你對我的問題的評論;我正在爲客戶端 - >服務器套接字通信製作一個DLL。我想讓Socket類自動打開兩個線程。一個用於接收來自網絡流的消息,另一個用於發送它們。爲了讓最終用戶變得簡單,我讓他們發送兩個類對象作爲參數;一個處理收到的消息,一個發送它們。這兩個類將需要*一些*強制變量/函數,但最終用戶會被告知。你的建議解決了這個問題,所以謝謝。 – natli 2012-02-27 14:54:48
沒問題,很高興幫助。 – 2012-02-27 15:48:28