Hi All,
I'm doing a large amount of file handling on a separate thread and would like to update a UI thread based progress bar. I wanted a simple way to update it and this seems to work.
I was wondering if anyone saw anything dangerous or just terribly wrong with this technique. I think the code below is simple to follow but I'm attaching the zipped project just in case.
(Code below should be attached as a full project; clicking the button should start a UI timer that updates a progress bar with a value provided by a timer executing on a separate thread)
I know the example is ultra-simplistic but I wanted to make sure the concept of sharing a variable across threads without SyncLock is OK, and the clear subject of the discussion.
Please suggest alternate coding techniques that you like; I'd like this to be more of a discussion than just a simple Q/A.
Thanks,
Nick
I'm doing a large amount of file handling on a separate thread and would like to update a UI thread based progress bar. I wanted a simple way to update it and this seems to work.
I was wondering if anyone saw anything dangerous or just terribly wrong with this technique. I think the code below is simple to follow but I'm attaching the zipped project just in case.
(Code below should be attached as a full project; clicking the button should start a UI timer that updates a progress bar with a value provided by a timer executing on a separate thread)
Code:
Public Class Form1
Private progressBarUpdateTimer As System.Threading.Timer
Private progressBarUpdateAutoEvent As System.Threading.AutoResetEvent
Private tcbProgressBarUpdate As System.Threading.TimerCallback
'Variable used on different threads; it seems to work but is it safe??
Private currentValue As Single
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
progressBarUpdateAutoEvent = New System.Threading.AutoResetEvent(False)
tcbProgressBarUpdate = AddressOf GrabbingDataDelegate
progressBarUpdateTimer = New System.Threading.Timer(tcbProgressBarUpdate, progressBarUpdateAutoEvent, 1000, 500)
End Sub
Private Sub GrabbingDataDelegate(stateInfo As Object)
'Updates class private variable
currentValue += 1
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ProgressBar1.Value = currentValue
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
currentValue = 0
Timer1.Enabled = True
End Sub
End Class
I know the example is ultra-simplistic but I wanted to make sure the concept of sharing a variable across threads without SyncLock is OK, and the clear subject of the discussion.
Please suggest alternate coding techniques that you like; I'd like this to be more of a discussion than just a simple Q/A.
Thanks,
Nick