title: c# Win Form - The CLR has been unable to transition from COM context
body: <p><strong>SQL version</strong> : SQL Server 2008 R2 Standard Edition<br>
  <strong>Application</strong> : .Net 3.5 (Windows Form)</p>
  
  <p>This is the error i am receiving after running my code</p>
  
  <blockquote>
    <p>The CLR has been unable to transition from COM context 0xe88270 to COM context 0xe88328 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.</p>
  </blockquote>
  
  <p>Following code produces the above error <strong>sometimes</strong>. Most probably after 24,000+ records have been inserted it gives the error.</p>
  
  <p><strong>Objective of the code</strong><br>
  The code is written to insert dummy entry to test my application</p>
  
  <pre><code>Random rnd = new Random();
  
  string Data = "";
  
  for (int i = 0; i &lt; 2000000; i++)
  {
        Data = "Insert Into Table1(Field1)values('" + rnd.Next(0, 200000000) + "');" + Environment.NewLine +
               "Insert Into Table1(Field1)values('" + rnd.Next(0, 200000000) + "');" + Environment.NewLine +
               "Insert Into Table1(Field1)values('" + rnd.Next(0, 200000000) + "');" + Environment.NewLine +
               "Insert Into Table1(Field1)values('" + rnd.Next(0, 200000000) + "');" + Environment.NewLine +
               "Insert Into Table1(Field1)values('" + rnd.Next(0, 200000000) + "');" + Environment.NewLine +
               "Insert Into Table1(Field1)values('" + rnd.Next(0, 200000000) + "');";
        ExecuteQuery(Data);//Error is displayed here
  }
  </code></pre>
  
  <p>Code of "ExecuteQuery"</p>
  
  <pre><code>SqlConnection Conn = new SqlConnection("Connection String");
  
  if (Conn == null)
  {
        Conn = new SqlConnection(Program.ConnString);
  }
  if (Conn.State == ConnectionState.Closed)
  {
        Conn.Open();
  }
  else
  {
        Conn.Close();
        Conn.Open();
  }
  
  SqlCommand cmd = new SqlCommand();
  cmd.Connection = Conn;
  cmd.CommandTimeout = 600000;
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = strsql;
  cmd.ExecuteNonQuery();
  Conn.Close();
  </code></pre>
  
  <p><strong>Note</strong> :- I have written multiple insert statements that are exact same in the query that is because it will reduce the no. of queries the SQL has to handle</p>
  
  <p><strong>Question</strong><br>
  How can i optimize my code to prevent the error from occuring?</p>