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

瘦欲@ 提交于 2019-12-06 15:33:06

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

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!