@@ -25,7 +25,7 @@ public class AnalysisService : IDisposable
25
25
{
26
26
#region Private Fields
27
27
28
- private Runspace analysisRunspace ;
28
+ private RunspacePool analysisRunspacePool ;
29
29
private PSModuleInfo scriptAnalyzerModuleInfo ;
30
30
private string [ ] activeRules ;
31
31
private string settingsPath ;
@@ -101,9 +101,19 @@ public AnalysisService(IConsoleHost consoleHost, string settingsPath = null)
101
101
try
102
102
{
103
103
this . SettingsPath = settingsPath ;
104
- this . analysisRunspace = RunspaceFactory . CreateRunspace ( InitialSessionState . CreateDefault2 ( ) ) ;
105
- this . analysisRunspace . ThreadOptions = PSThreadOptions . ReuseThread ;
106
- this . analysisRunspace . Open ( ) ;
104
+ var sessionState = InitialSessionState . CreateDefault2 ( ) ;
105
+
106
+ // import PSScriptAnalyzer in all runspaces
107
+ sessionState . ImportPSModule ( new string [ ] { "PSScriptAnalyzer" } ) ;
108
+
109
+ // runspacepool takes care of queuing commands for us so we do not
110
+ // need to worry about executing concurrent commands
111
+ this . analysisRunspacePool = RunspaceFactory . CreateRunspacePool ( sessionState ) ;
112
+
113
+ // one runspace for code formatting and the other for markers
114
+ this . analysisRunspacePool . SetMaxRunspaces ( 2 ) ;
115
+ this . analysisRunspacePool . ThreadOptions = PSThreadOptions . ReuseThread ;
116
+ this . analysisRunspacePool . Open ( ) ;
107
117
ActiveRules = IncludedRules . ToArray ( ) ;
108
118
InitializePSScriptAnalyzer ( ) ;
109
119
}
@@ -186,11 +196,11 @@ public Hashtable GetPSSASettingsHashtable(IDictionary<string, Hashtable> ruleSet
186
196
/// </summary>
187
197
public void Dispose ( )
188
198
{
189
- if ( this . analysisRunspace != null )
199
+ if ( this . analysisRunspacePool != null )
190
200
{
191
- this . analysisRunspace . Close ( ) ;
192
- this . analysisRunspace . Dispose ( ) ;
193
- this . analysisRunspace = null ;
201
+ this . analysisRunspacePool . Close ( ) ;
202
+ this . analysisRunspacePool . Dispose ( ) ;
203
+ this . analysisRunspacePool = null ;
194
204
}
195
205
}
196
206
@@ -305,7 +315,12 @@ private void EnumeratePSScriptAnalyzerRules()
305
315
private void InitializePSScriptAnalyzer ( )
306
316
{
307
317
FindPSScriptAnalyzer ( ) ;
318
+
319
+ // this import is redundant if we are importing the
320
+ // module while creating the runspace, but it helps
321
+ // us log the import related messages.
308
322
ImportPSScriptAnalyzer ( ) ;
323
+
309
324
EnumeratePSScriptAnalyzerRules ( ) ;
310
325
}
311
326
@@ -381,7 +396,7 @@ private async Task<IEnumerable<PSObject>> InvokePowerShellAsync(string command,
381
396
{
382
397
using ( var powerShell = System . Management . Automation . PowerShell . Create ( ) )
383
398
{
384
- powerShell . Runspace = this . analysisRunspace ;
399
+ powerShell . RunspacePool = this . analysisRunspacePool ;
385
400
powerShell . AddCommand ( command ) ;
386
401
foreach ( var kvp in paramArgMap )
387
402
{
0 commit comments