Friday, September 6, 2013

What does 'InvokeRequired' and 'Invoke' mean in .Net?

What does 'InvokeRequired' and 'Invoke' mean in .Net?

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.

No comments:

Post a Comment