title: High CPU usage during generating CSV file from SQL Server view using C# and Powershell
body: <p>I am generating CSV file from SQL Server view with Powershell to enable users download it from our ASP Web Forms web site: </p>
  
  <p>Powershell script:</p>
  
  <pre><code>Push-Location $PWD;Import-Module -Name SQLPS;Invoke-Sqlcmd -Query 'SELECT 1' ` -Database  *** `  -username '***' -password '***' -Server localhost |Out-Null;Pop-Location;Invoke-Sqlcmd -Query 'query here' ` -Database *** ` -username '***' -password '***' -Server ***| Export-Csv -NoTypeInformation ` -Path 'C:\****\products.csv' ` -Encoding UTF8;
  </code></pre>
  
  <p>C# code:</p>
  
  <pre><code>using (PowerShell PowerShellInstance = PowerShell.Create())
   {
      PowerShellInstance.AddScript(powerShellScript);                    
      Collection&lt;PSObject&gt; PSOutput = PowerShellInstance.Invoke();
   } 
  </code></pre>
  
  <p>There are 71784 rows in the view, csv file size is 12Mb. It takes about 15 second and CPU usage increases by 40% during file generation from Web forms site. </p>
  
  <p>When the same script is ran directly from Powershell console it seems that culprit is actually Powershell:
  <a href="https://i.stack.imgur.com/fv8jm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fv8jm.png" alt="enter image description here"></a></p>
  
  <p>Obviously it is not ok for production. We have hundreds of users who will need to generate this file with some specific parameters for each user(I can not serve the same file).</p>
  
  <p>So far I tried:</p>
  
  <pre><code>Thread thread1 = new Thread(builder.GenerateCsvFile); 
  thread1.Priority = System.Threading.ThreadPriority.Lowest;
  thread1.Start(); 
  </code></pre>
  
  <p>I am not sure that using Thread is a good idea in the first place, anyway CPU usage is about the same when using Thread. Any advice how to decrease CPU usage with C# code? OR any other low resource usage approach to this?</p>