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
As Joel and Matthew mention, BeginInvoke will execute a delegate asynchronously. As Matthew says, this MSDN article covers that well.
However, if you're trying to do some background work in a WinForms application, I recommend you check out the background worker control. It will be more familiar to developers used to the WinForms event-driven model.
As mentioned by Joel - BeginInvoke() will execute the delegate Asynchronously - and you will need to setup an Async callback to retrieve the return value if the target returns data (using EndInvoke).
The following link is a good article on using Delegates for Async Programming: http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx
Also (this is in C# - sorry) you can handle the callback using lambda expressions:
The best analogy that I've found to explain delegates it's a testament or your last will.
It's a set of instructions that of course you write before you die, and you leave it in a safe place. Then after your death, your attorney will execute those instructions...
Delegates are used mostly when the code that wants to execute the actions doesn't knows the enough details of what that action should be, you can view it as a sequence of actions to be executed at the appropriate time.
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.
In this case, I might not use a delegate, since you need to re-delegate back to the UI thread to update the buttons. You can use Application.DoEvents inside the loop to make your UI responsive while updating it.
Call
.BeginInvoke()
rather than.Invoke()
.