6
6
using Microsoft . PowerShell . EditorServices . Utility ;
7
7
using System ;
8
8
using System . Linq ;
9
- using System . Management . Automation . Runspaces ;
10
9
using System . Threading . Tasks ;
11
10
using Microsoft . PowerShell . EditorServices . Console ;
11
+ using System . Management . Automation . Runspaces ;
12
12
using System . Management . Automation ;
13
13
using System . Collections . Generic ;
14
14
using System . Text ;
@@ -24,7 +24,7 @@ public class AnalysisService : IDisposable
24
24
{
25
25
#region Private Fields
26
26
27
- private const int NumRunspaces = 2 ;
27
+ private const int NumRunspaces = 1 ;
28
28
private RunspacePool analysisRunspacePool ;
29
29
private PSModuleInfo scriptAnalyzerModuleInfo ;
30
30
@@ -332,13 +332,6 @@ private async Task<PSObject[]> GetDiagnosticRecordsAsync<TSettings>(
332
332
}
333
333
334
334
private PSObject [ ] InvokePowerShell ( string command , IDictionary < string , object > paramArgMap )
335
- {
336
- var task = InvokePowerShellAsync ( command , paramArgMap ) ;
337
- task . Wait ( ) ;
338
- return task . Result ;
339
- }
340
-
341
- private async Task < PSObject [ ] > InvokePowerShellAsync ( string command , IDictionary < string , object > paramArgMap )
342
335
{
343
336
using ( var powerShell = System . Management . Automation . PowerShell . Create ( ) )
344
337
{
@@ -349,16 +342,33 @@ private async Task<PSObject[]> InvokePowerShellAsync(string command, IDictionary
349
342
powerShell . AddParameter ( kvp . Key , kvp . Value ) ;
350
343
}
351
344
352
- var result = await Task . Factory . FromAsync ( powerShell . BeginInvoke ( ) , powerShell . EndInvoke ) ;
353
- if ( result == null )
345
+ var result = new PSObject [ 0 ] ;
346
+ try
354
347
{
355
- return new PSObject [ 0 ] ;
348
+ result = powerShell . Invoke ( ) ? . ToArray ( ) ;
349
+ }
350
+ catch ( CmdletInvocationException ex )
351
+ {
352
+ // We do not want to crash EditorServices for exceptions caused by cmdlet invocation.
353
+ // Two main reasons that cause the exception are:
354
+ // * PSCmdlet.WriteOutput being called from another thread than Begin/Process
355
+ // * CompositionContainer.ComposeParts complaining that "...Only one batch can be composed at a time"
356
+ Logger . Write ( LogLevel . Error , ex . Message ) ;
356
357
}
357
358
358
- return result . ToArray ( ) ; ;
359
+ return result ;
359
360
}
360
361
}
361
362
363
+ private async Task < PSObject [ ] > InvokePowerShellAsync ( string command , IDictionary < string , object > paramArgMap )
364
+ {
365
+ var task = Task . Run ( ( ) => {
366
+ return InvokePowerShell ( command , paramArgMap ) ;
367
+ } ) ;
368
+
369
+ return await task ;
370
+ }
371
+
362
372
#endregion //private methods
363
373
}
364
374
}
0 commit comments