title: Use Task.Run with Synchronous method inside a foreach loop
body: <p>I am trying to find a best possible approach to RUN synchronous C# method parallel. For this I opted for <code>Task.Run()</code> inside a foreach loop. ie, Add all the synchronous methods to tasks and use <code>Task.WhenAll(tasks).Wait()</code> to perform all the tasks parallel.</p>
  
  <p>Sorry if I am using <code>Task</code> without its actual purpose. I am doing this because <code>DBContext</code> is NOT thread safe and I have <code>Mandatory</code> to use single DBContext per Transaction/DB record. So, I thought making my method <code>async</code> is not useful as all the tasks i perform inside a method are dependent to one another. So, I thought its better RUN list of same tasks simultaneously.</p>
  
  <p>NOTE: I ran this program and I can see the Tasks run in parallel without any issue and the records created aren't sequential. So, Its confirmed that the tasks can parallel.</p>
  
  <p>Please help me to suggest whether my implementation is OK for long run.</p>
  
  <p><strong>Code</strong></p>
  
  <pre><code>    public void MainMethod()
      {
          foreach (var x in _ListUser)
              tasks.Add(Task.Run(() =&gt; Update1Record(x)));
          Task.WhenAll(tasks).Wait();
      }
      public string Update1Record(UserViewModel objUser)
      {
          using (var VibrantDbContext = new VIBRANT())
          using (var AuditDb = new VibrantAuditEntities())
          using (var VibrantTransaction = VibrantDbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
          using (var AuditTransaction = AuditDb.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
          {
              try
              {
                  VibrantDbContext.Database.Initialize(force: false);
                  AuditDb.Database.Initialize(force: false);
                  VibrantDbContext.Configuration.AutoDetectChangesEnabled = false;
                  var _ObjUserItem = FillupDateTimeValues(objUser);
                  ImportToDB(_ObjUserItem, 0, VibrantDbContext, AuditDb);
                  BuildImportLog(objUser, VibrantDbContext, AuditDb);
                  VibrantDbContext.SaveChanges();
                  AuditDb.SaveChanges();
                  VibrantTransaction.Commit();
                  AuditTransaction.Commit();
              }
              catch (Exception ex)
              {
                  VibrantTransaction.Rollback();
                  AuditTransaction.Rollback();
                  throw;
              }
          }
          return "S";
      }
  </code></pre>