[英]Multithreaded WinForm Calling a PowerShell Script .Net 3.5
Will I run into any issues executing a single PowerShell script from a multithreaded WinForm app? 从多线程WinForm应用程序执行单个PowerShell脚本时,是否会遇到任何问题? My main concern is related to the WinForm threads locking the PowerShell script.
我主要关心的是与锁定PowerShell脚本的WinForm线程有关。
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();
}
}
What if toProcess
contains the value 1,000,000. 如果
toProcess
包含值1,000,000,该怎么toProcess
。 then you're spawning 1m threads. 那么您将产生1m个线程。 The
_Proc.Start()
is not blocking, so your threads will be finished in no-time, but you will probably don't want to spawn 1m processes. _Proc.Start()
没有阻塞,因此您的线程将立即完成,但是您可能不希望产生1m个进程。
If you want to process them parallel, add the process.WaitForExit();
如果要并行处理它们,请添加
process.WaitForExit();
(to make the executing process blocking) in the thread and put them on the ThreadPool
. (以阻止正在执行的进程)在线程中,然后将它们放在
ThreadPool
。 (The ThreadPool
limits the concurrent threads (so also processes)) (
ThreadPool
限制了并发线程(也限制了进程))
or 要么
use the Parallel.Foreach()
with the MaxDegreeOfParallelism
property. 将
Parallel.Foreach()
与MaxDegreeOfParallelism
属性一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.