66using Microsoft . PowerShell . EditorServices . Utility ;
77using System ;
88using System . Linq ;
9- using System . Management . Automation . Runspaces ;
109using System . Threading . Tasks ;
1110using Microsoft . PowerShell . EditorServices . Console ;
11+ using System . Management . Automation . Runspaces ;
1212using System . Management . Automation ;
1313using System . Collections . Generic ;
1414using System . Text ;
@@ -24,7 +24,7 @@ public class AnalysisService : IDisposable
2424 {
2525 #region Private Fields
2626
27- private const int NumRunspaces = 2 ;
27+ private const int NumRunspaces = 1 ;
2828 private RunspacePool analysisRunspacePool ;
2929 private PSModuleInfo scriptAnalyzerModuleInfo ;
3030
@@ -332,13 +332,6 @@ private async Task<PSObject[]> GetDiagnosticRecordsAsync<TSettings>(
332332 }
333333
334334 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 )
342335 {
343336 using ( var powerShell = System . Management . Automation . PowerShell . Create ( ) )
344337 {
@@ -349,16 +342,33 @@ private async Task<PSObject[]> InvokePowerShellAsync(string command, IDictionary
349342 powerShell . AddParameter ( kvp . Key , kvp . Value ) ;
350343 }
351344
352- var result = await Task . Factory . FromAsync ( powerShell . BeginInvoke ( ) , powerShell . EndInvoke ) ;
353- if ( result == null )
345+ var result = new PSObject [ 0 ] ;
346+ try
354347 {
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 ) ;
356357 }
357358
358- return result . ToArray ( ) ; ;
359+ return result ;
359360 }
360361 }
361362
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+
362372 #endregion //private methods
363373 }
364374}
0 commit comments