我正在尝试编写一个VB.net(框架4.5),它将查看1000个代理服务器是否已启动,并且我希望一次批量处理它们。 我已经尝试使用线程,线程池并绘制了一个空白,所以现在已经转移到使用Parallel方法,但输出不按顺序。
Public Sub Get_Items_Click(sender As Object, e As EventArgs) Handles Get_Items_Button.Click
Dim ParallelOpts As New ParallelOptions()
ParallelOpts.MaxDegreeOfParallelism = 10
Parallel.For(0, 2000, ParallelOpts, AddressOf ProxySub)
End Sub
Public Sub ProxySub(ByVal ItemNumber As Integer)
‘Do some work … See if Proxy is up and running using HTTPWebRequest and output to a SyncLock textbox
End sub
ProxySub对不同的服务器进行HTTPWebRequest,因此我理解它们返回的顺序并不总是与它们的发送顺序相同,但我需要同步输出。
如果设置了“ParallelOpts.MaxDegreeOfParallelism = 10”,为什么我看到输出从0跳到40?
输出如下; 0,40,5,63,7,23,1,9等等。
我如何同步它以便输出顺序,即; 0,1,2,3,4等等。
非常感谢您提供的任何意见
答案 0 :(得分:0)
它不足以同步你的文本框。您需要在UI线程上进行更改。
Public Sub ProxySub(ByVal ItemNumber As Integer)
'Do some work … See if Proxy is up and running using HTTPWebRequest and output to a SyncLock textbox
OnResultReceived(new MyResultObject(itemNumber, data))
End Sub
Public Sub OnResultReceived(result As MyResultObject)
'Any thread can call this
If InvokeRequired Then
'It wasn't the UI thread. Call this method again from the ui thread.
Me.BeginInvoke(Sub() OnResultReceived(result))
Else
'This is now on the ui thread
'Add the sorted results to the textbox
TextBox.Text = ...
End If
End Sub
要按顺序添加文本,您可以将结果存储在sortedlist中并使用string.join或将文本框更改为可以处理排序的listview。