问题
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.
回答1:
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
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/18662905/what-does-invokerequired-and-invoke-mean-in-net