我试图从线程池中更新主表单中的进度条,但到目前为止我尝试的所有内容都更新了进度条的值,但没有更新它的外观,尝试了几种不同的方式,仍然可以&# 39;找到解决方案。有人可以指出我正确的方向,每次线程完成时,将form1上的进度条更新为1.
Imports System.Threading
Public Class Form1
Dim arry As New List(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
BackgroundWorker1.RunWorkerAsync()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim ii As Integer = 2000
For a As Integer = 0 To ii
arry.Add(a)
Next
ProgressBar1.Maximum = arry.Count
ThreadPool.SetMaxThreads(4, 4)
Dim doneEvents(arry.Count) As ManualResetEvent
Dim r As New Random()
For i As Integer = 0 To arry.Count
doneEvents(i) = New ManualResetEvent(False)
Dim f = New stuff(r.Next(20, 40), doneEvents(i))
ThreadPool.QueueUserWorkItem(AddressOf f.ThreadPoolCallBack, i)
Next
For Each handle As WaitHandle In doneEvents
handle.WaitOne()
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCalls = False
End Sub
Private Delegate Sub FillDelegate()
Public Sub Fill()
If ProgressBar1.InvokeRequired Then
ProgressBar1.BeginInvoke(New FillDelegate(AddressOf Fill))
Else
ProgressBar1.Increment(1)
ProgressBar1.Refresh()
End If
End Sub
End Class
Public Class stuff
Private _doneEvent As ManualResetEvent
Private _n As Integer
Public ReadOnly Property N() As Integer
Get
Return _n
End Get
End Property
Sub New(ByVal n As Integer, ByVal doneEvent As ManualResetEvent)
_n = n
_doneEvent = doneEvent
End Sub
Public Sub ThreadPoolCallBack(ByVal threadContext As Object)
Try
Dim threadIndex As Integer = CType(threadContext, Integer)
Console.WriteLine("thread {0} started...", threadIndex)
Form1.Fill()
Console.WriteLine("thread {0} finished...", threadIndex)
Catch ex As Exception
Console.WriteLine("error in threadPoolCallback")
Console.WriteLine(ex.Message)
Finally
_doneEvent.Set()
End Try
End Sub
End Class