Hello, and welcome to my article about the MethodInvoker Delegate. Delegates are funny things, as you will soon see.
Let's jump right in, shall we?
Delegates contain a reference to a method inside a delegate object. This object can, in turn, be passed to code that calls the referenced method, allowing the method to be invoked to be unknown at compile time.
Delegates (C# Programming Guide) at MSDN has a more detailed explanation of delegates.
If you have never heard the term "Threads" before, let me explain. Any application makes use of threads to either show you information or a screen, or to allow for long running tasks to complete. Now, threads are tricky and data is tricky. Sometimes, you will encounter a situation that may possibly freeze your application due to a long running task. So, instead of slamming all the code into one form, you have several threads. Each thread can run independently without affecting any other threads or user process.
Here is more information regarding threads.
Multithreaded applications can perform multiple tasks at the same time. This means that tasks that could possibly hold up other tasks can execute on separate threads. Multithreaded applications are more responsive to user input.
This method executes the specified delegate on the thread that owns the control's underlying window handle. A control's Invoke method searches from the control upwards, up the parent chain until it finds a control or form that has a window handle. The Control.Invoke method is explained here.
The MethodInvoker Delegate
The MethodInvoker Delegate provides a delegate that is used to invoke a method that doesn't return anything; in other words, a sub procedure instead of a function. MethodInvoker can be used when you need a delegate but don't want to define a new delegate.
Here is a more detailed explanation of the MethodInvoker delegate.
An example of how you can utilize the MethodInvoker follows:
Private Sub button1_Click(ByVal sender As Object, _ ByVal e As EventArgs) If InvokeRequired Then ' If it is not on UI thread, invoke it using' ' methodInvoker' Dim methodInvoker As MethodInvoker = AddressOf updateUI Invoke(methodInvoker) Else ' It is on main UI thread, so you can update the UI' updateUI() End If End Sub Private Sub updateUI() ' Update any UI here .....' End Sub
Here it shows how to spawn a separate thread, so to speak, to update the user interface.
There are many options available to you when deciding how to approach threading. MethodInvoker is quite a good choice because it is quick and easy and less cumbersome than most other options.