.Net中的"InvokeRequired"和"Invoke"是什么意思?

编程入门 行业动态 更新时间:2024-10-26 04:30:42
本文介绍了.Net中的"InvokeRequired"和"Invoke"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经在我正在处理的一些程序中使用线程进行了大量工作,而我一直很好奇到底在做什么.

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 Sub

Me.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"是什么意思?

本文发布于:2023-11-03 01:15:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1553888.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:quot   Net   Invoke   InvokeRequired

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!