1

I have been working a lot with threading in a few programs I am working on, and I have always been curious as to what exactly something is doing.

Take for instance the following code, which is ran from a thread to update the UI:

Public Sub UpdateGrid() 
    If Me.InvokeRequired Then 
        Me.Invoke(New MethodInvoker(AddressOf UpdateGrid)) 
    Else 
        DataGridView1.DataSource = dtResults 
        DataGridView1.Refresh() 
        btnRun.Text = "Run Query" 
        btnRun.ForeColor = Color.Black 
    End If 
End Sub

What exactly does the Me.InvokeRequired check for, and what exactly is the Me.Invoke doing? I understand that somehow it gives me access to items on the UI, but how does it accomplish this?

On a side note, let's say UpdateGrid() was a function that returned a value and had a required parameter. How would I pass the parameter and how would I get the return value after I call the Me.Invoke method? I tried this without the parameter but 'nothing' was getting returned, and I couldn't figure out how to attach the parameter when invoking.

Nicholas Post
  • 1,857
  • 1
  • 18
  • 31

3 Answers3

3

Me.InvokeRequired is checking to see if it's on the UI thread if not it equals True, Me.Invoke is asking for a delegate to handle communication between the diff threads.

As for your side note. I typically use an event to pass data - this event is still on the diff thread, but like above you can delegate the work.

Public Sub UpdateGrid() 
    'why ask if I know it on a diff thread
    Me.Invoke(Sub() 'lambda sub
               DataGridView1.DataSource = dtResults 
               DataGridView1.Refresh() 
               btnRun.Text = "Run Query" 
               btnRun.ForeColor = Color.Black 
              End Sub)
End Sub
OneFineDay
  • 9,004
  • 3
  • 26
  • 37
1

Invoke() makes sure that the invoked method will be invoked on the UI thread. This is useful when you want to make an UI adjustment in another thread (so, not the UI thread).

InvokeRequired checks whether you need to use the Invoke() method.

ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
1

From the example you posted, the section that needs to update the UI is part of the Invoke logic, while the retrieval of the data can be done on a worker/background thread.

If Me.InvokeRequired Then

This checks to see if Invoke() is necessary or not.

Me.Invoke(New MethodInvoker(AddressOf UpdateGrid)) 

This guarantees that this logic will run on the UI thread and since it is handling interacting with the UI (grid), then if you tried to run this on a background thread it would not work.

Karl Anderson
  • 34,606
  • 12
  • 65
  • 80