I am generating CSV file from SQL Server view with Powershell to enable users download it from our ASP Web Forms web site:
Powershell script:
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;
C# code:
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(powerShellScript);
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
}
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.
When the same script is ran directly from Powershell console it seems that culprit is actually Powershell:
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).
So far I tried:
Thread thread1 = new Thread(builder.GenerateCsvFile);
thread1.Priority = System.Threading.ThreadPriority.Lowest;
thread1.Start();
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?