0

I can get a progress bar to increment inside the Do loop but it massively affects the speed of the loop. How can i keep track of progress of the Do Until loop without affecting it?

Do Until temp = pbTemp2
temp+= 1
progressbar1.increment(1) '<--- i dont want this in here but still need to track the progress
loop
bifo
  • 3
  • 2

1 Answers1

0

The middle ground between what Visual Vincent proposed and a BackgroudWorker.
(I'm assuming this is related to .NET WinForms).

Crate a Thread to perform some work, and use a SynchronizationContext to queue the results the process to the UI context.

The SynchronizationContext will then dispatch an asynchronous message to the synchronization context through a SendOrPostCallback delegate, a method that will perform its elaboration in that context. The UI thread in this case.

The asynchronous message is sent using SynchronizationContext.Post method.

The UI thread will not freeze and can be used to perform other tasks in the meanwhile.

How this works:
- Define a method which will interact with some UI control:
SyncCallback = New SendOrPostCallback(AddressOf Me.UpdateProgress)
- Initialize a new Thread, specifying the worker method that the thread will use.
Dim pThread As New Thread(AddressOf Progress)
- Starting the thread, it's possible to pass a parameter to the worker method, in this case is the maximum value of a progress bar.
pThread.Start(MaxValue)
- When the worker method needs to report back its progress to the (UI) context, this is done using the asychronous Post() method of the SynchronizationContext.
SyncContext.Post(SyncCallback, temp)

Here, the thread is started using a Button.Click event, but it could be anything else.

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
Jimi
  • 29,621
  • 8
  • 43
  • 61