我已经设法在一个线程中获取了我想要的数据,但是我无法将数据传回我的主线程(GUI)。
我正在从线程中的网络流中获取数据,然后需要将其传递给我的主线程以传递给其他类等。
我已经看到它提到使用backgroundworker,但由于我期望它定期收集数据并且永远不会停止,我认为这个单独的线程是最好的,但我对多线程很新。
如果线程是正确的方法,我怎样才能将数据从它传递回我的主线程以便将其用于其他东西?我已经看到代表和事件提到了很多,但看不出我如何用这些传递数据?
由于
答案 0 :(得分:6)
请研究这个例子,并告诉我它是否符合您的要求:
需要控制: lstItems(ListBox),btnStart(按钮),btnStop(按钮),Timer1(定时器)。
Form1代码:
Public Class Form1
Dim p_oStringProducer As StringProducer
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
p_oStringProducer = New StringProducer
p_oStringProducer.Start()
Timer1.Enabled = True
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) _
Handles btnStop.Click
Timer1.Enabled = False
p_oStringProducer.Stop()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim asQueue As Concurrent.ConcurrentQueue(Of String) =
p_oStringProducer.MessageQueue
While asQueue.Count > 0
Dim sItem As String = Nothing
asQueue.TryDequeue(sItem)
lstItems.Items.Add(sItem)
End While
End Sub
End Class
StringProducer代码:
Imports System.Threading.Tasks
Public Class StringProducer
Private p_fKeepRunning As Boolean
Private p_oTask As task
Private p_aMessageQueue As Concurrent.ConcurrentQueue(Of String)
Private p_iNextMessageId As Integer
Public ReadOnly Property MessageQueue As _
Concurrent.ConcurrentQueue(Of String)
Get
Return p_aMessageQueue
End Get
End Property
Sub New()
p_oTask = New Task(AddressOf TaskBody)
p_aMessageQueue = New Concurrent.ConcurrentQueue(Of String)
p_iNextMessageId = 0
End Sub
Public Sub Start()
p_fKeepRunning = True
p_oTask.Start()
End Sub
Public Sub [Stop]()
p_fKeepRunning = False
End Sub
Private Sub TaskBody()
While p_fKeepRunning
Threading.Thread.Sleep(2000)
p_aMessageQueue.Enqueue("Message #" & p_iNextMessageId)
p_iNextMessageId += 1
End While
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
Me.Stop()
End Sub
End Class
这没有经过广泛测试,但它应该让你有一个良好的开端。