I am writing a server program that does some basic threading. It needs to update some UI controls and I learned how to use delegates such that everything is thread safe. For example, here's my delegate that allows me to update a TextBox control from a thread:
Private Delegate Sub AddMessageToTXTDelegate(ByVal lst As TextBox, ByVal str1 As String)
Private Sub AddMessageToTXT(ByVal txt As TextBox, ByVal str1 As String)
Try
If Me.InvokeRequired Then
Dim addTXT As New AddMessageToTXTDelegate(AddressOf AddMessageToTXT)
Me.BeginInvoke(addTXT, New Object() {txt, str1})
Else
txt.Text = str1
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
Throw (ex)
End Try
End Sub
Now i need to update a counter and I figured the same pattern would apply. I put together the following delegate:
Private Delegate Sub IncrementCounterDelegate(ByVal ctr As Integer)
Private Sub IncrementCounter(ByVal ctr As Integer)
Try
If Me.InvokeRequired Then
Dim incCtr As New IncrementCounterDelegate(AddressOf IncrementCounter)
Me.BeginInvoke(incCtr, New Object() {ctr})
Else
ctr += 1
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
Throw (ex)
End Try
End Sub
The problem is that my counter is not being incremented. When I trace this with debug, the "ctr += 1" statement gets executed but the actual counter remains at zero. I'm thinking I should be passing the counter in by reference.
Can anyone provide some advice here? Thanks!
\cbf