title: How to use delegate and event in multi-threading c#
body: <p>I'm experimenting with multi-thread coding. If I would like to execute processes in parallel. Say, I would like to query table A, table B, and table C simultaneously. Within each thread, I am doing SqlCommand .ExecuteReader like this:</p>
  
  <p>using System.Collections.Generic;
  using System.Data.SqlClient;</p>
  
  <pre><code>namespace MultiThread2
  {
      public class TableFieldArray
      {
          public string TableName { get; set; }
          public string FieldName { get; set; }
      }
  
      static class MTProcess
      {
          const string connStr = "server=***;database=***;user id=***;password=***";
  
          public static event GetStringArrayResult OnRecordsFoundMTS;
  
          public static void GetStringArrays(TableFieldArray[] tableFieldArray)
          {
              foreach (TableFieldArray tf in tableFieldArray)
              {
                  Thread thread = new Thread(() =&gt;
                  {
                      ST_Process stp = new ST_Process(connStr);
                      stp.ListOfFieldValue(tf.TableName, tf.FieldName);
                      stp.OnRecordsFound += new GetStringArrayResult(getEvent);
                  });
  
                  thread.Start();
              }
          }
  
          private static void getEvent(string[] result)
          {
              OnRecordsFoundMTS(result);
              return;
          }
  
  // ---------------
  
      public delegate void GetStringArrayResult(string[] output);
  
      class ST_Process
      {
          public event GetStringArrayResult OnRecordsFound;
  
          private readonly string _connStr;
  
          public ST_Process(string connectionString)
          {
              _connStr = connectionString;
          }
  
          public void ListOfFieldValue(string tableName, string fieldName)
          {
              List&lt;string&gt; result = new List&lt;string&gt;();
              using (SqlConnection sqlConn = new SqlConnection(_connStr))
              {
                  sqlConn.Open();
                  string sqlText = string.Format("SELECT TOP 100 {0} FROM {1} ", fieldName, tableName);
                  using (SqlCommand sqlcmd = new SqlCommand(sqlText, sqlConn) { CommandType = System.Data.CommandType.Text })
                  {
                      var r = sqlcmd.ExecuteReader();
                      while (r.Read())
                      {
                          result.Add(r[fieldName].ToString());
                      }
                      OnRecordsFound(_result.ToArray());
                  }
                  sqlConn.Close();
              }
          }
      }
  }
  </code></pre>
  
  <p>The problem is, when executed in separate threads, OnRecordsFound(_result.ToArray()) causes object reference not set to an instance of an object exception error. Any idea how to make this setup work with multi-thread environment?</p>