日期:2014-05-19  浏览次数:20813 次

求助:线程间操作无效
如何解决:线程间操作无效:   从不是创建控件“textbox2”的线程访问它。

也就是说:
对话框中有一textbox控件
Thread   ftp_thread   =   new   Thread(new   ThreadStart(ReceiveData));
.....
public   void   ReceiveData()
{
      textbox.enable=false;
}

会出现以上错误     如何解决   谢谢


------解决方案--------------------
用委托,给个示例:
delegate void SetTextCallback(string text);建立委托

private void SetText(string text)
{
if (this.listBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.listBox1.Items.Add(text);
}
}

private void Accp()
{
try
{
MyServer = new IPEndPoint(myIp, Int32.Parse(textBox2.Text));
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(MyServer);
sock.Listen(50);
SetText( "主机: " + textBox1.Text + "端口: " + textBox2.Text + " 开始监听。。。\r\n ");
while (true)
{
accsock = sock.Accept();
if (accsock.Connected == true)
{

SetText( "与客户端建立连接 "); //线程间操作listBox~
Thread thread = new Thread(new ThreadStart(Round));
thread.Start();
}
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
------解决方案--------------------
private void SetText(string text)
{
if (this.textbox.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textbox.Text = text;
}
}

------解决方案--------------------
可以通过将 可以通过将 CheckForIllegalCrossThreadCalls 属性的值设置为 false 来禁用此异常。这会使控件以与在 Visual Studio 2003 下相同的方式运行。
属性的值设置为 false 来禁用此异常。这会使控件以与在 Visual Studio 2003 下相同的方式运行。

在初始化函数中,或者构造函数中加上CheckForIllegalCrossThreadCalls = false;