Showing posts with label invoke. Show all posts
Showing posts with label invoke. Show all posts

Saturday, July 27, 2013

Delegates, Invoke, InvokeRequired


Question: What is InvokeRequired? Why this word is so difficult and what is it do? 

Answer: InvokeRequired is a property of a control which tells whether or not you can safely access the control. It is a boolean to check if you are on the UI thread before you try to update a form or control from a worker thread. 

If the property is True, then an invocation is required to access the control as the caller is on different thread than the one that owns the control's handle.

The invocation is performed by calling the control's Invoke or BeginInvoke method. 
You create a delegate, which is an object that contains the reference to a method. Then we pass this delegate to Invoke or BeginInvoke method which essentially call the reference method again but on thread that owns the control's handle.

Summary:
InvokeRequired asks 'Am I on the right thread?', if so carry on, else I need a delegate.

I got help and understanding of this from: 

Accessing Controls from Worker Threads


HTH.


Saturday, July 20, 2013

Delegates vb.net

Delegates are function pointers that store function address.

There are 3 steps to understand Delegates:
  1. Defining Delegate
  2. Instantiating Delegate
  3. Assigning Address of function to Delegate

Nothing fancy; just memorize the above steps to absorb the whole idea.

'How to define?
Public Delegate Sub testfile(Byval filename As String)

'instantiating the delegate
Dim mytestfile As testfile

Private Sub DoWork()
    'now assign the address of function to the delegate
    mytestfile = AddressOf FileTester

    'it can be called as
    mytestfile("test.txt"
    'or
    mytestfile.Invoke("test.txt")
End Sub
Public Sub FileTester(ByRef filename As String)
     MsgBox(filename)
End Sub


Now FileTester is really the function will be called which just shows the filename

Happy coding!