Isn’t the use of delegates to help with some asynchronous cases? I tried the following but my UI still hangs. When on earth do you use delegates?
Public Class Form1 Private Delegate Sub testDelegate() Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click Dim d As testDelegate = New testDelegate(AddressOf Add) d.Invoke() End Sub Private Sub Add() For i As Integer = 0 To 10000 TextBox1.Text = i + 1 Next End Sub End Class
It’s kind of ironic, but everybody’s favorite answer (use BeginInvoke) is not in fact correct. The delegate target method will execute on a threadpool thread. You are not allowed to touch controls on a thread other than the thread that created them, almost always the program’s main thread.
If you try it using the .NET framework version 2.0 and up in the debugger, the loop will immediately terminate with an IllegalOperationException. To correct that, you’ll have to use Control.BeginInvoke(). A completely different animal from the delegate’s BeginInvoke() method btw.
Now here’s the irony, your loop will now dispatch 10,000 delegate invocation requests to the UI thread. It will spend several seconds executing them, not getting around to doing any real work. Like dispatch the TextBox’s Paint event. Or respond to any user input. You are in fact much worse off than before.
I doubt this helps much explaining delegates. Maybe you can pick a better example, something that doesn’t try to update controls.