dori naji
dori naji

Reputation: 980

Multithreading InvalidOperationException C#

i have a button.when i click this button i make a new thread then goes to ThreadProcSafe method and i want over there to set the the response into the richtextbox.but when i try to do that i always take an InvalidOperationException and says to me cross thread operation not valid: Control accessed from a thread other than the thread it was created on.any suggestions?

 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;
        }
    }

Upvotes: 2

Views: 612

Answers (1)

ChrisWue
ChrisWue

Reputation: 19020

Because you are doing this richTextBox1.Text = sr.ReadToEnd(); inside your ThreadProcSafe. What you probably wanted to do is this:

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);
}

Note that you should wrap your streams into using statements so that they get disposed properly.

Upvotes: 2

Related Questions