Multithreading InvalidOperationException C#
本文关键字:InvalidOperationException Multithreading | 更新日期: 2023-09-27 18:12:44
我有一个按钮。当我点击这个按钮时,我创建了一个新线程然后转到ThreadProcSafe方法,我想在那里将响应设置到richtextbox中。但是当我试着做的时候我总是用InvalidOperationException告诉我cross线程操作无效:从其他线程访问的控件创建它的线程。有什么建议吗?
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;
}
}
因为您在ThreadProcSafe
中执行此richTextBox1.Text = sr.ReadToEnd();
。您可能想要这样做:
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);
}
请注意,您应该将您的流包装成using
语句,以便它们得到正确处理。