多线程无效操作异常C#
我有一个按钮。当我点击这个按钮时,我创建了一个新的线程 然后转到ThreadProcSafe方法,我想在那里 将响应设置到richtextbox中。但是当我尝试这样做时 我总是破例对我说“十字架” 线程操作无效:从非线程访问控件 创建它的线程。有什么建议吗多线程无效操作异常C#,c#,multithreading,delegates,richtextbox,C#,Multithreading,Delegates,Richtextbox,我有一个按钮。当我点击这个按钮时,我创建了一个新的线程 然后转到ThreadProcSafe方法,我想在那里 将响应设置到richtextbox中。但是当我尝试这样做时 我总是破例对我说“十字架” 线程操作无效:从非线程访问控件 创建它的线程。有什么建议吗 delegate void SetTextCallback(string text); private Thread demoThread = null; private void Go_Click(object sen
delegate void SetTextCallback(string text);
private Thread demoThread = null;
private void Go_Click(object sender,EventArgs e)
{
this.demoThread =new Thread(new ThreadStart(this.ThreadProcSafe));
this.demoThread.Start();
}
// This method send a request get response
private void ThreadProcSafe()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
this.SetText(richTextBox1.Text);
}
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.richTextBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.richTextBox1.Text = text;
}
}
因为您正在执行此操作
richTextBox1.Text=sr.ReadToEnd()代码>在ThreadProcSafe
中。您可能想做的是:
private void ThreadProcSafe()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string res = sr.ReadToEnd();
sr.Close();
this.SetText(res);
}
请注意,您应该使用
语句将流包装成,以便正确地处理它们