views:

81

answers:

2

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

+1  A: 

A thread safe way to increment an integer can be achieved using System.Threading.Interlocked.Increment. You should use this and avoid the delegate.

Edit

I'm not sure why your trying to use a delegate. Your incrementing a value object which can be done on any thread. You just can't update UI controls from other threads.

If your trying to make this threadsafe then you need to introduce locking using a Monitor (as one example), or using the Interlocked's Increment method.

JoshBerke
+1  A: 

You are passing the counter by value, so ctr += 1 increments the function's argument. You need to pass the counter by reference, or just increment a private field with InterlockedIncrement — no delegates or invoke required.

Anton Tykhyy