我已经在我正在处理的一些程序中使用线程进行了大量工作,而我一直很好奇到底在做什么.
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.
以下面的代码为例,该代码是从线程运行以更新UI的:
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 SubMe.InvokeRequired到底要检查什么,Me.Invoke到底要做什么?我知道,它以某种方式使我可以访问UI上的项目,但是它是如何实现的呢?
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?
另一方面,假设UpdateGrid()是一个返回值并具有必需参数的函数.调用Me.Invoke方法后,如何传递参数以及如何获得返回值?我尝试了没有参数的尝试,但是没有返回"nothing",并且我无法弄清楚在调用时如何附加参数.
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.
推荐答案Me.InvokeRequired正在检查它是否在UI线程上,如果不等于True,则Me.Invoke要求委托来处理之间的通信diff线程.
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.
至于你的旁注.我通常使用一个事件来传递数据-该事件仍在diff线程上,但是像上面一样,您可以委派工作.
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更多推荐
.Net中的"InvokeRequired"和"Invoke"是什么意思?
发布评论