0

I know that when you want to display a value from inside a thread , that you need to use delegates and invoke else there will be thrown illegal cross thread exception . In the following example I dont use delegates . Is it bad or not ? Should i avoid it and just use delegates to update the UI ?

Public Class Form1

    Public Class Test
        Public Property i As Integer = 0
        Public Event ReturnValue(v As Integer)
        Public Sub Start()
            Dim T As Threading.Thread = New Threading.Thread(Sub()
                                                                 While True
                                                                     Threading.Thread.Sleep(100)
                                                                     i += 1
                                                                     RaiseEvent ReturnValue(i)
                                                                 End While
                                                             End Sub)
            T.Start()
        End Sub
    End Class

    Public WithEvents TestInstance As New Test

    Private Sub UpdateUI(ByVal v As Integer) Handles TestInstance.ReturnValue
        Invoke(Sub()
                   Label1.Text = v.ToString
               End Sub)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        TestInstance.Start()
    End Sub

End Class
George S.
  • 1
  • 1
  • 1
    `Sub()` is still put in a delegate. The important part is `Invoke`. – Ry- Sep 24 '18 at 18:09
  • So this is just a quicker way to write the code ? – George S. Sep 24 '18 at 18:10
  • 1
    You're still using a delegate. Just because it's a lambda expression doesn't mean it's not a delegate. The INVOKE is what you're really needing for cross-thread safety. Named delegates in that situation are so you can perform an invoke when needed, and run without an Invoke when not needed. There is an overhead associated with invoke after all. – Stephen Wrighton Sep 24 '18 at 18:11
  • 1
    A delegate is just a pointer to a function/method. On its own it hasn't got anything to do with thread-safety. Like the others have said it's the `Invoke()` call that matters here. I recommend reading [this answer of mine](https://stackoverflow.com/a/45571728/3740093), where I explain a little more thoroughly how marshalling to the UI works. – Visual Vincent Sep 24 '18 at 19:54
  • 1
    I guess you are referring to a specific example where a delegate is defined, and used in the thread constructor. Ok, you can do that. But when you just pass a `Sub()` you are actually using this Thread constructor: `Thread(ThreadStart)`, and check out the ThreadStart inheritance - ThreadStart : **Delegate** : Object. **So this is just a quicker way to write the code ?** Yes - read Vincent's answer thoroughly and understand it. You would benefit from understanding the concepts therein. – djv Sep 24 '18 at 21:50

0 Answers0