title: BackgroundWorker Thread fails on access of a Windows Form control
body: <p>I am trying to update a Windows Forms control from a background worker process, as shown in the code below. Unfortunately, I am getting the following error:</p>
  
  <blockquote>
    <p>Cross-thread operation not valid: Control 'richTextBox1' accessed from a thread other than the thread it was created on.</p>
  </blockquote>
  
  <p>Here is the code I am using:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Linq;
  using System.Text;
  using System.Windows.Forms;
  using System.Net;
  using System.IO;
  using System.Text.RegularExpressions;
  
  namespace WindowsFormsApplication1 {
      public partial class Form1 : Form {
          private CookieContainer cookies;
          public Form1() {
              InitializeComponent();
              backgroundWorker1.DoWork += 
                  new DoWorkEventHandler(backgroundWorker1_DoWork);    
          }
  
          public string od_auth(string s) {    
              if (s.Contains(":")) {
                  string[] acc = s.Split(':');
                  cookies = new CookieContainer();
                  HttpWebResponse res;
                  try {
                      HttpWebRequest req = 
                          (HttpWebRequest)HttpWebRequest.Create(
                              "http://m.site.ru/dk?" + 
                              "bk=GuestMain" + 
                              "&amp;st.cmd=main" + 
                              "&amp;tkn=1110" +
                              "&amp;fr.posted=set" +
                              "&amp;fr.needCaptcha=" + 
                              "&amp;fr.login=" + acc[0] + 
                              "&amp;fr.password=" + acc[1] +
                              "&amp;fr.remember=on" + 
                              "&amp;button_login=%D0%92%D0%BE%D0%B9%D1%82%D0%B8"
                          );
                      req.AllowAutoRedirect = false;
                      req.Method = "HEAD";
                      req.CookieContainer = cookies;
                      req.UserAgent = "Opera/9.80 (Windows NT 6.1; U; ru) " +
                                      "Presto/2.2.15 Version/10.10";
                      req.ContentType = "application/x-www-form-urlencoded";
                      res = (HttpWebResponse)req.GetResponse();
                      res.Close();
  
                      string cook = "";
                      try {
                          if (res.Headers["Location"].Contains("cmd=userMain")) {    
                              cook = "AUTHCODE=" + Regex.Match(res.Headers["Set-Cookie"], @"HCODE=(?&lt;id&gt;[^;]+);").Groups["id"].Value + "; ";
                              cook += "JSESSIONID=" + Regex.Match(res.Headers["Set-Cookie"], @"ESSIONID=(?&lt;id&gt;[^;]+);", RegexOptions.RightToLeft).Groups["id"].Value + ";";
                              richTextBox1.Text += "[+] Авторизовались успешно на " + acc[0] + ":" + acc[1] + "\r\n";
                              return cook;
                          } else {
                              cook = "badacc";
                              richTextBox1.Text += "[-] Аккаунт " + acc[0] + ":" + acc[1] + " невалидный\r\n";
                              return cook;
                          }
                      } catch {
                          cook = "badacc";
                          richTextBox1.Text += "[-] Аккаунт " + acc[0] + ":" + acc[1] + " невалидный\r\n";
                          return cook;
                      }
                  }
                  catch { richTextBox1.Text += "[?] network error \r\n"; ;return "err"; }
              }
  
              richTextBox1.Text += "[?] some error \r\n";
              return "err";
          }
  
          public void od_info_changer(string cook) {
              HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://m.site.ru/dk?bk=UserSettingsProfile&amp;st.cmd=userSettingsProfile&amp;tkn=2154");
              request.Method = "POST";
              request.Headers.Add("Cookie: "+cook);
              request.AllowAutoRedirect = false;
              request.ContentType = "application/x-www-form-urlencoded";
              byte[] EncodedPostParams = Encoding.UTF8.GetBytes("fr.posted=set&amp;fr.name=D1%8F&amp;fr.surname=%D0&amp;fr.gender=1&amp;fr.birthday=12&amp;fr.bmonth=10&amp;fr.byear=1949&amp;fr.country=10414533690&amp;fr.city=%D0%95%D0%BA%D0%B0%D1%82%D0%B5%D1%80%D0%B8%D0%BD%D0%B1%D1%83%D1%80%D0%B3&amp;button_save=%D0%A1%D0%BE%D1%85%D1%80%D0%B0%D0%BD%D0%B8%D1%82%D1%8C");
              request.ContentLength = EncodedPostParams.Length;
              request.GetRequestStream().Write(EncodedPostParams, 0, EncodedPostParams.Length);
              request.GetRequestStream().Close();
  
              HttpWebResponse response = (HttpWebResponse)request.GetResponse();
              string html = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
              if (response.Headers["Location"].IndexOf("st.cmd=userSettings") != -1) {
                  richTextBox1.Text += "[+] Cменили пароль\r\n";
              } else {
                  richTextBox1.Text += "[-] Не смогли сменить имя\r\n";
              }               
          }
  
          List&lt;string&gt; accs=new List&lt;string&gt;();
          private void открытьАккаунтыToolStripMenuItem_Click(object sender, EventArgs e) {
              OpenFileDialog openFileDialog1 = new OpenFileDialog();
              openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
              if (openFileDialog1.ShowDialog() == DialogResult.OK) {
                  accs.Clear();
                  foreach (string s in File.ReadAllLines(openFileDialog1.FileName))
                      accs.Add(s);
  
                  richTextBox1.Text += "[+] Загрузили " + accs.Count.ToString() + " аккаунтов\n";
              }
          }
  
          private void Auth_Click(object sender, EventArgs e) {
              Auth.Enabled = false; // На время расчета блокируем опасные кнопки
              backgroundWorker1.RunWorkerAsync();
          }    
  
          public void go() {
              foreach (string acc in accs) {
                  string cook = od_auth(acc);
                  if (cook!="badacc")
                      od_info_changer(cook);
              }    
          }
  
          private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
              go();
          }
      }
  }
  </code></pre>
  
  <p>However, after loading up the <code>.txt</code> file and pressing my button, I receive:</p>
  
  <p><img src="https://i.stack.imgur.com/RnVQN.png" alt="this error message"></p>
  
  <p>What's going wrong?</p>