title: Task.WaitAll Method in C#.NET is is throwing an Exception in rare cases
body: <p>I'm using an API to get data and store it in Database. The problem is that API return only 50 records per a call, so to get more data in less time, we have used <strong>Parallel.For</strong> in the application. The code which I'm using below is saving the data in database successfully most of the times but it's throwing an exception in rare cases. The exception which it's throwing at rare cases is</p>
  
  <blockquote>
    <p>The tasks array included at least one null element. Parameter name: tasks | at System.Threading.Tasks.Task.WaitAll(Task[] tasks, Int32 millisecondsTimeout, CancellationToken cancellationToken) at System.Threading.Tasks.Task.WaitAll(Task[] tasks, Int32 millisecondsTimeout).</p>
  </blockquote>
  
  <p>I don't know the reason of the exception because most of the time it is giving the correct results and I can save data in database. Below is the code which I have written. Please help me with resolving this issue, I'm new to the parallel programing.</p>
  
  <pre><code>object objobject = new object();
  
  public void GetDataConcurrent()
  {
      var tasks = new List&lt;Task&gt;();
      ParallelOptions objParallelOptions = new ParallelOptions();
      CancellationTokenSource objCancellationTokenSource = new CancellationTokenSource();
      objParallelOptions.MaxDegreeOfParallelism = 3;
      objParallelOptions.CancellationToken = objCancellationTokenSource.Token;
      string CompletePostData = "PostData to send to API";
      string tException = string.Empty;
      int noOfrequests = 15;
      string jsonResponse=string.Empty; 
      try
      {
          Parallel.For(0, noOfrequests, objParallelOptions, (ChangeSetValue) =&gt;
          {
              tasks.Add(Task.Factory.StartNew(() =&gt;
              {
                  var webRequest = WebRequest.Create("http://urlofAPI");
                  webRequest.ContentType = "application/json";
                  webRequest.Method = "POST";
                  webRequest.Proxy = WebRequest.DefaultWebProxy;
                  webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
                  POSTDATA objPOSTDATA = new POSTDATA();
                  objPOSTDATA.CompletePostData = CompletePostData + ",'ChangeSetValue':'" +   (ChangeSetValue) + "'}";
                  string json = new      System.Web.Script.Serialization.JavaScriptSerializer().Serialize(objPOSTDATA);
                  var datatoSend = Encoding.UTF8.GetBytes(json);
                  webRequest.GetRequestStream().Write(datatoSend, 0, datatoSend.Length);
                  webRequest.GetReponseAsync().ContinueWith(t =&gt; 
                  {
                      if (t.Exception == null)
                      {
                          using (var sr = new StreamReader(t.Result.GetResponseStream()))
                          {
                              lock (objobject)
                              {
                                  string str = sr.ReadToEnd();
                                  jsonResponse = jsonResponse + str; 
                                  jsonResponse = jsonResponse.Replace("&lt;string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\"&gt;", string.Empty);
                                  jsonResponse = jsonResponse.Replace("&lt;/string&gt;", string.Empty);
                                  jsonResponse = jsonResponse.Substring(1, jsonResponse.Length - 2);
                                  SaveData();// Method to Save Data in Database by Deserializing the JSON Response
                                  jsonResponse = string.Empty;
                              }
                          }
                      }
                      else
                      {
                          tException = t.Exception.InnerException.Message;
                      }
                  }).Wait();
              }));
          });
          Task.WaitAll(tasks.ToArray());
      }
      catch (OperationCanceledException ex)
      {
          LogException(InsertLogInformation(ex.Message));
      }
      catch (AggregateException ex)
      {
          for (int j = 0; j &lt; ex.InnerExceptions.Count; j++)
          {
              LogException(InsertLogInformation(ex.Message));
          }
      }
      catch (Exception ex)
      {
          LogException(InsertLogInformation(ex.Message));
      }
  }
  
  public void SaveData()
  {
      //Method to Save Data in DataBase
  }
  
  public static class WebRequestExtensions
  {
      public static Task&lt;WebResponse&gt; GetReponseAsync(this WebRequest request)
      {
          return Task.Factory.FromAsync&lt;WebResponse&gt;(request.BeginGetResponse, request.EndGetResponse, null);
      }
  }
  
  public class POSTDATA
  {
      public string CompletePostData { get; set; }
  }
  </code></pre>