我的 InvokeRequied #2 有什么问题吗?
The first topic is What wrong with my InvokeRequied
I followed the answer that he recommended it to me but I found a new problem.
The result of below picture is cross thread exception.
What is wrong with my code ?
How to solve this problem ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 MSDN
InvokeRequired
可以即使在InvokeRequired
应为true
的情况下,也返回false
- 即在您在之前访问InvokeRequired
的情况下该控件/表单(或其父级)的句柄
已创建。基本上你的检查不完整,这导致了你看到的结果。
您需要检查
IsHandleCreated
- 如果这是false
,那么无论InvokeRequired
返回什么,您都需要使用Invoke
/BeginInvoke
。[更新]
但是:
这通常无法正常工作,因为
Invoke
/BeginInvoke
检查哪个线程创建了Handle
来发挥其魔力......[/UPDATE]
仅当
IsHandleCreated
为true
时,您才会根据InvokeRequired
返回的内容采取行动 - 类似于:[UPDATE]
因此,以下内容对于避免此问题非常重要
始终确保在首次访问 UI 线程以外的线程之前已创建
Handle
。根据 MSDN 你只需要引用
control .Handle
在 UI 线程中强制创建它 - 在您的代码中,这必须在您第一次从非 UI 线程的任何线程访问该控件/表单之前发生。[/更新]
According to MSDN
InvokeRequired
can returnfalse
even in cases whereInvokeRequired
should betrue
- namely in the case that you accessInvokeRequired
before theHandle
of that control/form (or a parent of it) has been created.Basically your check is incomplete which leads to the result you see.
You need to check
IsHandleCreated
- if that isfalse
then you would need to useInvoke
/BeginInvoke
regardless of whatInvokeRequired
returns.[UPDATE]
BUT:
This usually won't work robustly since
Invoke
/BeginInvoke
check which thread createdHandle
to do their magic...[/UPDATE]
Only if
IsHandleCreated
istrue
you act based on whatInvokeRequired
returns - something along the lines of:[UPDATE]
Thus the following is important to avoid this problem
Always make sure that the
Handle
is already created BEFORE the first access on a thread other than the UI thread.According to MSDN you just need to reference
control.Handle
in the UI thread to force it being created - in your code this must happen BEFORE the very first time you access that control/form from any thread that is not the UI thread.[/UPDATE]