Vb.net 使用进度条跟踪循环进度,而不影响循环速度

Vb.net 使用进度条跟踪循环进度,而不影响循环速度,vb.net,Vb.net,我可以在Do循环中获得一个进度条来增加,但是它会极大地影响循环的速度。如何在不影响Do-Until循环的情况下跟踪Do-Until循环的进度 Do Until temp = pbTemp2 temp+= 1 progressbar1.increment(1) '<--- i dont want this in here but still need to track the progress loop Do直到temp=pbTemp2 温度+=1 progressbar1.增量(1)“V

我可以在Do循环中获得一个进度条来增加,但是它会极大地影响循环的速度。如何在不影响Do-Until循环的情况下跟踪Do-Until循环的进度

Do Until temp = pbTemp2
temp+= 1
progressbar1.increment(1) '<--- i dont want this in here but still need to track the progress
loop
Do直到temp=pbTemp2
温度+=1

progressbar1.增量(1)“VisualVincent提出的建议与背景工人之间的中间立场。
(我假设这与.NET
WinForms
)有关。

包装一个线程以执行某些工作,并使用一个线程将处理结果排队到UI上下文中。

然后,
SynchronizationContext
将通过委托向同步上下文发送一条异步消息,委托方法将在该上下文中执行其细化。本例中的UI线程。

异步消息使用方法发送。

UI线程不会冻结,同时可用于执行其他任务。

工作原理:
-定义将与某些UI控件交互的方法:
SyncCallback=newsendorpostcallback(AddressOf Me.UpdateProgress)

-初始化新线程,指定线程将使用的辅助方法
将pThread设置为新线程(进度地址)

-启动线程时,可以将参数传递给worker方法,在这种情况下是进度条的最大值。
pThread.Start(MaxValue)

-当工作者方法需要向(UI)上下文报告其进度时,可以使用
SynchronizationContext
的异步
Post()
SyncContext.Post(SyncCallback,temp)

这里,线程是使用
按钮启动的。单击
事件,但它可以
还有别的吗。

导入系统线程
专用SyncContext作为SynchronizationContext
作为SendOrPostCallback的专用SyncCallback
私有子按钮1\u单击(发送者作为对象,e作为事件参数)处理按钮11。单击
SyncContext=WindowsFormsSynchronizationContext.Current
SyncCallback=New SendOrPostCallback(AddressOf Me.UpdateProgress)
Dim MaxValue为整数=ProgressBar1.最大值
将pThread调整为新线程(进度地址)
pThread.IsBackground=True
pThread.Start(最大值)
端接头
私有子UpdateProgress(状态为对象)
ProgressBar1.Value=CInt(状态)
端接头
私有子进程(参数作为对象)
Dim temp作为整数=0
Dim MaxValue As Integer=CType(参数,整数)
做
温度+=1
SyncContext.Post(SyncCallback,temp)
温度<最大值时循环
端接头

在后台线程中运行循环,并让它增加一个变量。然后在窗体/控件上放置一个计时器,让它根据变量不断更新进度条。您可以每x次递增一次。
Imports System.Threading

Private SyncContext As SynchronizationContext
Private SyncCallback As SendOrPostCallback

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button11.Click
    SyncContext = WindowsFormsSynchronizationContext.Current
    SyncCallback = New SendOrPostCallback(AddressOf Me.UpdateProgress)
    Dim MaxValue As Integer = ProgressBar1.Maximum

    Dim pThread As New Thread(AddressOf Progress)
    pThread.IsBackground = True
    pThread.Start(MaxValue)
End Sub

Private Sub UpdateProgress(state As Object)
    ProgressBar1.Value = CInt(state)
End Sub

Private Sub Progress(parameter As Object)
    Dim temp As Integer = 0
    Dim MaxValue As Integer = CType(parameter, Integer)
    Do
        temp += 1
        SyncContext.Post(SyncCallback, temp)
    Loop While temp < MaxValue
End Sub