跨线程操作无效:从创建它的线程以外的线程访问控制。 [英] Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.

查看:72
本文介绍了跨线程操作无效:从创建它的线程以外的线程访问控制。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连续循环,它创建控件。

面板是InvokeRequired = true和对象。

如何在这种情况下继续。

I have a continuous cycle, which creates the controls.
The panel is being InvokeRequired = true and the object.
how to proceed in this case.

While true
 sleep(2000)
 dim myType as myType
 sTh = New Thread(New ParameterizedThreadStart(AddressOf AddMoreControls))
 sTh.Start(myType)
Wend

  
 Delegate Sub sAddControl(ByVal pParam() As Object)
 Private Sub ssAddControl(ByVal pParam() As Object)
	 Try
		 Dim pn As Panel = CType(pParam(0), Panel)
		 Dim ctl As MyControl = CType(pParam(1), MyControl)
		 pn.Controls.Add(ctl)
	 Catch ex As Exception
		Throw ex
	 End Try
 End Sub

 Private Sub AddMoreControls(byval myType as myType)
	 try
		 Dim ctl As New MyControl
		 ctl.Name = "txt_1"
		 ctl.myType = myType

		 if GroupBox.InvokeRequired then

		 Dim pParam(1) As Object
			 pParam(0) = myPanel
			 pParam(1) = ctl
			 Dim d As New sAddControl(AddressOf ssAddControl)
			 GroupBox.Invoke(d, New Object() {pParam})
		 else
			myPanel.add(ctl)
		 end if 
	Catch ex As Exception
		msgbox (ex)
	End Try
 end sub





已添加代码块[/编辑]



Code block added[/Edit]

推荐答案

你真的不能在后台线程上做任何这个。所有控件都必须在UI线程上创建,否则你会遇到各种难以调试且无法解决的问题。



你仍然可以从后台线程执行此操作,但您必须在UI线程上调用方法来创建控件。你不能从UI线程以外的任何东西触摸任何控件或控件容器(比如向表单,面板,组框等添加控件)。
You really can''t do any of this on a background thread. All controls MUST be created on the UI thread or you''ll run into all kinds of problems that are extremely difficult to debug and can''t fix.

You can still do this from a background thread, but you must Invoke a method on the UI thread to create the controls. You cannot touch any control or control container (like adding controls to a form, panel, group box, ...) from anything other than the UI thread.


AddMoreControls以新的方式运行线程,在这个函数中创建的控件(ctl)将不会与Panel(UI线程)在同一个线程中。

这就是为什么我认为你的操作无效。

您应该在Invoked方法中包含控件的创建。

the AddMoreControls runs in a new Thread, the control (ctl) created in this function will not be in the same thread as the Panel (the UI Thread).
That''s why I think you have the invalid operation.
You should include the creation of the control in the Invoked method.
Delegate Sub sAddMoreControl(ByVal myType as myType)
Private Sub AddMoreControls(byval myType as myType)
try
  if GroupBox.InvokeRequired then
    Dim d As New sAddMoreControl(AddressOf AddMoreControls)
    GroupBox.Invoke(d, New Object() {myType})
  else
    Dim ctl As New MyControl
    ctl.Name = "txt_1"
    ctl.myType = myType
    myPanel.add(ctl)
  end if
Catch ex As Exception
  msgbox (ex)
End Try
end sub 





很抱歉如果我在VB.NET中犯了一些语法错误,我更多地使用C#语法。



Sorry if I made some syntax error in VB.NET, I use C# syntax more.


这篇关于跨线程操作无效:从创建它的线程以外的线程访问控制。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆