从多线程WinForm应用程序执行单个PowerShell脚本时会遇到任何问题吗?我主要关心的是WinForm线程锁定PowerShell脚本。
for (int i = 0; i <= toProcess; i++)
{
bWorker.ReportProgress(0, i.ToString());
PowerShellProcs workPs = new PowerShellProcs();
workPs.CusId = CustomerDataTable.Rows[i]["CustomerID"].ToString();
ThreadStart threadDelegate = new ThreadStart(workPs.DoPs);
Thread newThread = new Thread(threadDelegate);
newThread.Name = CustomerDataTable.Rows[i]["CustomerID"].ToString();
newThread.Start();
if (toProcess == i)
{
resetEvent.Set();
}
Thread.Sleep(1000);
//threads.Add(newThread);
}
class PowerShellProcs
{
public string CusId;
public void DoPs()
{
String customerId = CusId;
var scriptfile = @"c:ProcessCustomer.ps1";
Process _Proc = new Process();
_Proc.StartInfo = "Powershell.exe";
_Proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
_Proc.StartInfo.Arguments = "'" + customerId + "' ";
_Proc.Start();
}
}
如果toProcess
包含值1000000会怎样。那么你就产生了100万条线程。_Proc.Start()
没有阻塞,所以您的线程很快就会完成,但您可能不想生成1m进程。
如果您想并行处理它们,请在线程中添加process.WaitForExit();
(使执行进程阻塞),并将它们放在ThreadPool
上。(ThreadPool
限制并发线程(因此也限制进程)
或
使用具有MaxDegreeOfParallelism
属性的Parallel.Foreach()
。