diff --git a/src/Analyzers/CSharp/CodeFixes/AddBraces/CSharpAddBracesCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/AddBraces/CSharpAddBracesCodeFixProvider.cs index 64b8379d9d73f..7a79db543eed4 100644 --- a/src/Analyzers/CSharp/CodeFixes/AddBraces/CSharpAddBracesCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/AddBraces/CSharpAddBracesCodeFixProvider.cs @@ -22,13 +22,12 @@ internal sealed class CSharpAddBracesCodeFixProvider() : SyntaxEditorBasedCodeFi public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.AddBracesDiagnosticId]; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Add_braces, nameof(CSharpAnalyzersResources.Add_braces)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -47,7 +46,5 @@ protected override Task FixAllAsync( return embeddedStatement is null ? currentStatement : currentStatement.ReplaceNode(embeddedStatement, SyntaxFactory.Block(embeddedStatement)); }); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs index 10f9731c35dec..21b1f57ce35cb 100644 --- a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs @@ -28,7 +28,7 @@ internal sealed class ConvertNamespaceCodeFixProvider() : SyntaxEditorBasedCodeF public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseBlockScopedNamespaceDiagnosticId, IDEDiagnosticIds.UseFileScopedNamespaceDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); @@ -41,7 +41,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) }); RegisterCodeFix(context, title, equivalenceKey); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs index 1423b58a90466..ce30e5a5f9c41 100644 --- a/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs @@ -32,10 +32,9 @@ internal sealed partial class ConvertSwitchStatementToExpressionCodeFixProvider( public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConvertSwitchStatementToExpressionDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Convert_switch_statement_to_expression, nameof(CSharpAnalyzersResources.Convert_switch_statement_to_expression)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/FixIncorrectConstraint/CSharpFixIncorrectConstraintCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/FixIncorrectConstraint/CSharpFixIncorrectConstraintCodeFixProvider.cs index f49ac21d07316..37dc4babed8c8 100644 --- a/src/Analyzers/CSharp/CodeFixes/FixIncorrectConstraint/CSharpFixIncorrectConstraintCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/FixIncorrectConstraint/CSharpFixIncorrectConstraintCodeFixProvider.cs @@ -60,7 +60,7 @@ private static bool TryGetConstraint( return enumOrDelegateKeyword.Kind() is SyntaxKind.EnumKeyword or SyntaxKind.DelegateKeyword; } - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; @@ -69,8 +69,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpCodeFixesResources.Fix_constraint, nameof(CSharpFixIncorrectConstraintCodeFixProvider)); } - - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs index cd2bade5c9d23..5380d0a2c659b 100644 --- a/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs @@ -36,10 +36,9 @@ internal sealed partial class CSharpInlineDeclarationCodeFixProvider() : SyntaxE public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.InlineDeclarationDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Inline_variable_declaration, nameof(CSharpAnalyzersResources.Inline_variable_declaration)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs index d981874b1ac5c..4b2d38b7b33b0 100644 --- a/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs @@ -35,13 +35,12 @@ internal sealed partial class InvokeDelegateWithConditionalAccessCodeFixProvider protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Properties.ContainsKey(WellKnownDiagnosticTags.Unnecessary); - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Simplify_delegate_invocation, nameof(CSharpAnalyzersResources.Simplify_delegate_invocation)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -50,8 +49,6 @@ protected override Task FixAllAsync( cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, diagnostic, cancellationToken); } - - return Task.CompletedTask; } private static void AddEdits( diff --git a/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpAddYieldCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpAddYieldCodeFixProvider.cs index 221a096de9638..d4e855619b8a4 100644 --- a/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpAddYieldCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpAddYieldCodeFixProvider.cs @@ -81,7 +81,7 @@ public override ImmutableArray FixableDiagnosticIds return CodeAction.Create( CSharpCodeFixesResources.Replace_return_with_yield_return, - _ => Task.FromResult(document.WithSyntaxRoot(root)), + async _ => document.WithSyntaxRoot(root), nameof(CSharpCodeFixesResources.Replace_return_with_yield_return)); } diff --git a/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs index a1ebbb3099f84..89b4449d922a4 100644 --- a/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs @@ -104,7 +104,7 @@ internal sealed class CSharpChangeToIEnumerableCodeFixProvider() : AbstractItera type.ToMinimalDisplayString(model, node.SpanStart), ienumerableGenericSymbol.ToMinimalDisplayString(model, node.SpanStart)); - return CodeAction.Create(title, _ => Task.FromResult(newDocument), title); + return CodeAction.Create(title, async _ => newDocument, title); } private static bool TryGetIEnumerableSymbols( diff --git a/src/Analyzers/CSharp/CodeFixes/MakeAnonymousFunctionStatic/CSharpMakeAnonymousFunctionStaticCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeAnonymousFunctionStatic/CSharpMakeAnonymousFunctionStaticCodeFixProvider.cs index 122513c0fc3b8..ccd3760f77478 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeAnonymousFunctionStatic/CSharpMakeAnonymousFunctionStaticCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeAnonymousFunctionStatic/CSharpMakeAnonymousFunctionStaticCodeFixProvider.cs @@ -24,18 +24,16 @@ internal sealed class CSharpMakeAnonymousFunctionStaticCodeFixProvider() : Synta public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.MakeAnonymousFunctionStaticDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix( context, CSharpAnalyzersResources.Make_anonymous_function_static, nameof(CSharpAnalyzersResources.Make_anonymous_function_static), context.Diagnostics[0].Severity > DiagnosticSeverity.Hidden ? CodeActionPriority.Default : CodeActionPriority.Low); - - return Task.CompletedTask; } - protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var generator = editor.Generator; @@ -44,7 +42,5 @@ protected override Task FixAllAsync(Document document, ImmutableArray generator.WithModifiers(node, generator.GetModifiers(node).WithIsStatic(true))); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs index 980bfb21c6060..f0a378e30b634 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs @@ -22,19 +22,16 @@ internal sealed class MakeLocalFunctionStaticCodeFixProvider() : SyntaxEditorBas public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.MakeLocalFunctionStaticDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Make_local_function_static, nameof(CSharpAnalyzersResources.Make_local_function_static)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var localFunctions = diagnostics.SelectAsArray(d => d.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken)); foreach (var localFunction in localFunctions) editor.ReplaceNode(localFunction, MakeLocalFunctionStaticCodeFixHelper.AddStaticModifier); - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProvider.cs index 46b3d5b773af4..e3d71640b338f 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProvider.cs @@ -35,7 +35,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) return WrapFixAsync( context.Document, [diagnostic], - (document, localFunction, captures) => + async (document, localFunction, captures) => { context.RegisterCodeFix( CodeAction.Create( @@ -43,8 +43,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) cancellationToken => MakeLocalFunctionStaticCodeFixHelper.MakeLocalFunctionStaticAsync(document, localFunction, captures, cancellationToken), nameof(CSharpCodeFixesResources.Pass_in_captured_variables_as_arguments)), diagnostic); - - return Task.CompletedTask; }, context.CancellationToken); } diff --git a/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs index 3e8d66b3a3a39..1e35d71fd4a78 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs @@ -103,7 +103,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) }; } - protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; var generator = editor.Generator; @@ -138,7 +138,5 @@ protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -57,8 +57,6 @@ protected override Task FixAllAsync( MakeStatementAsynchronous(editor, statementToFix); } } - - return Task.CompletedTask; } private static void MakeStatementAsynchronous(SyntaxEditor editor, SyntaxNode statementToFix) diff --git a/src/Analyzers/CSharp/CodeFixes/MakeStructFieldsWritable/CSharpMakeStructFieldsWritableCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeStructFieldsWritable/CSharpMakeStructFieldsWritableCodeFixProvider.cs index b9b1909edbdc0..8ed6dd53ed0c6 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeStructFieldsWritable/CSharpMakeStructFieldsWritableCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeStructFieldsWritable/CSharpMakeStructFieldsWritableCodeFixProvider.cs @@ -25,13 +25,12 @@ internal sealed class CSharpMakeStructFieldsWritableCodeFixProvider() : SyntaxEd public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.MakeStructFieldsWritable]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Make_readonly_fields_writable, nameof(CSharpAnalyzersResources.Make_readonly_fields_writable)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -61,7 +60,5 @@ protected override Task FixAllAsync( } } } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyCodeFixProvider.cs index 5fbc782c52ab5..0620060a17a4f 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyCodeFixProvider.cs @@ -26,13 +26,12 @@ internal sealed class CSharpMakeStructMemberReadOnlyCodeFixProvider() : SyntaxEd public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.MakeStructMemberReadOnlyDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Make_member_readonly, nameof(CSharpAnalyzersResources.Make_member_readonly)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -95,7 +94,7 @@ protected override Task FixAllAsync( } } - return Task.CompletedTask; + return; TNode UpdateReadOnlyModifier(TNode node, bool add) where TNode : SyntaxNode { diff --git a/src/Analyzers/CSharp/CodeFixes/MakeStructReadOnly/CSharpMakeStructReadOnlyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeStructReadOnly/CSharpMakeStructReadOnlyCodeFixProvider.cs index 697d799433afc..5c0d95266813b 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeStructReadOnly/CSharpMakeStructReadOnlyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeStructReadOnly/CSharpMakeStructReadOnlyCodeFixProvider.cs @@ -24,13 +24,12 @@ internal sealed class CSharpMakeStructReadOnlyCodeFixProvider() : SyntaxEditorBa public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.MakeStructReadOnlyDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Make_struct_readonly, nameof(CSharpAnalyzersResources.Make_struct_readonly)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -45,7 +44,5 @@ protected override Task FixAllAsync( typeDeclaration, (current, generator) => generator.WithModifiers(current, generator.GetModifiers(current).WithIsReadOnly(true))); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs index 8cde1756070e7..0c3edf144a055 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs @@ -27,7 +27,7 @@ internal sealed class ArrowExpressionClausePlacementCodeFixProvider() : CodeFixP public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ArrowExpressionClausePlacementDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -37,7 +37,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, [diagnostic], c), nameof(CSharpCodeFixesResources.Place_token_on_following_line)), context.Diagnostics); - return Task.CompletedTask; } private static async Task UpdateDocumentAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs index 13ba977508273..6861028305f64 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs @@ -27,7 +27,7 @@ internal sealed class ConditionalExpressionPlacementCodeFixProvider() : CodeFixP public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConditionalExpressionPlacementDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -37,7 +37,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, [diagnostic], c), nameof(CSharpCodeFixesResources.Place_token_on_following_line)), context.Diagnostics); - return Task.CompletedTask; } private static async Task UpdateDocumentAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementCodeFixProvider.cs index 6f37b38c9fce5..9ad0f6b96a3fb 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementCodeFixProvider.cs @@ -28,7 +28,7 @@ internal sealed class ConsecutiveBracePlacementCodeFixProvider() : CodeFixProvid public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConsecutiveBracePlacementDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -38,7 +38,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, diagnostic, c), nameof(CSharpCodeFixesResources.Remove_blank_lines_between_braces)), context.Diagnostics); - return Task.CompletedTask; } private static Task UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementCodeFixProvider.cs index fdb85c447f743..9330903991dac 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementCodeFixProvider.cs @@ -27,7 +27,7 @@ internal sealed class ConstructorInitializerPlacementCodeFixProvider() : CodeFix public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConstructorInitializerPlacementDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -37,7 +37,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, [diagnostic], c), nameof(CSharpCodeFixesResources.Place_token_on_following_line)), context.Diagnostics); - return Task.CompletedTask; } private static async Task UpdateDocumentAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs index 2cb1247d4ee5b..d7074853367a2 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs @@ -30,7 +30,7 @@ internal sealed class EmbeddedStatementPlacementCodeFixProvider() : CodeFixProvi public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.EmbeddedStatementPlacementDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -40,7 +40,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) c => FixAllAsync(document, [diagnostic], c), nameof(CSharpCodeFixesResources.Place_statement_on_following_line)), context.Diagnostics); - return Task.CompletedTask; } public static async Task FixAllAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs index f7fbba37cde3c..e940f7dcb0c68 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs @@ -30,7 +30,7 @@ internal sealed partial class CSharpRemoveConfusingSuppressionCodeFixProvider() public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.RemoveConfusingSuppressionForIsExpressionDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostics = context.Diagnostics; @@ -49,8 +49,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) c => FixAllAsync(document, diagnostics, negate: true, c), NegateExpression), context.Diagnostics); - - return Task.CompletedTask; } private static async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnneccessaryUnsafeModifier/CSharpRemoveUnnecessaryUnsafeModifierCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnneccessaryUnsafeModifier/CSharpRemoveUnnecessaryUnsafeModifierCodeFixProvider.cs index f45b506f74031..7fce5e71ad404 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnneccessaryUnsafeModifier/CSharpRemoveUnnecessaryUnsafeModifierCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnneccessaryUnsafeModifier/CSharpRemoveUnnecessaryUnsafeModifierCodeFixProvider.cs @@ -27,15 +27,13 @@ internal sealed class CSharpRemoveUnnecessaryUnsafeModifierCodeFixProvider() : C { public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.RemoveUnnecessaryUnsafeModifier]; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(CodeAction.Create( AnalyzersResources.Remove_unnecessary_unsafe_modifier, cancellationToken => FixAllAsync(context.Document, context.Diagnostics, cancellationToken), nameof(AnalyzersResources.Remove_unnecessary_unsafe_modifier)), context.Diagnostics); - - return Task.CompletedTask; } private static async Task FixAllAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastCodeFixProvider.cs index d901756a39dfb..51775f24b3145 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastCodeFixProvider.cs @@ -28,10 +28,9 @@ internal sealed partial class CSharpRemoveUnnecessaryCastCodeFixProvider() : Syn public sealed override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId]; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Remove_Unnecessary_Cast, nameof(AnalyzersResources.Remove_Unnecessary_Cast)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider.cs index bb128253e29e2..5f1e8d2232182 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider.cs @@ -25,13 +25,12 @@ internal sealed partial class CSharpRemoveUnnecessaryDiscardDesignationCodeFixPr public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.RemoveUnnecessaryDiscardDesignationDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Remove_unnessary_discard, nameof(CSharpAnalyzersResources.Remove_unnessary_discard)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -77,7 +76,5 @@ protected override Task FixAllAsync( break; } } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionCodeFixProvider.cs index 07b8668580569..8d9c0513e355c 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionCodeFixProvider.cs @@ -31,13 +31,12 @@ internal sealed partial class CSharpRemoveUnnecessaryLambdaExpressionCodeFixProv public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.RemoveUnnecessaryLambdaExpressionDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Remove_unnecessary_lambda_expression, nameof(CSharpAnalyzersResources.Remove_unnecessary_lambda_expression)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -72,8 +71,6 @@ protected override Task FixAllAsync( } } } - - return Task.CompletedTask; } private static IEnumerable TakeComments(SyntaxTriviaList triviaList) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveCodeFixProvider.cs index ce5e78e396373..2d783e424ada3 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveCodeFixProvider.cs @@ -31,7 +31,7 @@ public override ImmutableArray FixableDiagnosticIds IDEDiagnosticIds.RemoveUnnecessaryNullableDirectiveDiagnosticId, ]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -40,11 +40,9 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) else RegisterCodeFix(context, CSharpAnalyzersResources.Remove_unnecessary_nullable_directive, nameof(CSharpAnalyzersResources.Remove_unnecessary_nullable_directive), diagnostic); } - - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -89,8 +87,6 @@ protected override Task FixAllAsync( node, node.ReplaceToken(token, token.WithLeadingTrivia(leadingTrivia))); } - - return Task.CompletedTask; } private static bool HasPrecedingBlankLine(SyntaxTriviaList leadingTrivia, int index) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessarySuppressions/CSharpRemoveUnnecessaryNullableWarningSuppressionsCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessarySuppressions/CSharpRemoveUnnecessaryNullableWarningSuppressionsCodeFixProvider.cs index 78deaf667bcf0..2a7afd050b1fe 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessarySuppressions/CSharpRemoveUnnecessaryNullableWarningSuppressionsCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessarySuppressions/CSharpRemoveUnnecessaryNullableWarningSuppressionsCodeFixProvider.cs @@ -28,15 +28,13 @@ internal sealed class CSharpRemoveUnnecessaryNullableWarningSuppressionsCodeFixP { public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.RemoveUnnecessaryNullableWarningSuppression]; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(CodeAction.Create( AnalyzersResources.Remove_unnecessary_suppression, cancellationToken => FixSingleDocumentAsync(context.Document, context.Diagnostics, cancellationToken), nameof(AnalyzersResources.Remove_unnecessary_suppression)), context.Diagnostics); - - return Task.CompletedTask; } private static async Task FixSingleDocumentAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs index fc80ca447fac3..f8d26dfee78da 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs @@ -24,7 +24,7 @@ internal sealed class CSharpRemoveUnreachableCodeCodeFixProvider() : SyntaxEdito public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics[0]; @@ -37,8 +37,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) : CodeActionPriority.Default; RegisterCodeFix(context, CSharpCodeFixesResources.Remove_unreachable_code, nameof(CSharpCodeFixesResources.Remove_unreachable_code), priority); - - return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) @@ -47,7 +45,7 @@ protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) private static bool IsSubsequentSection(Diagnostic diagnostic) => diagnostic.Properties.ContainsKey(CSharpRemoveUnreachableCodeDiagnosticAnalyzer.IsSubsequentSection); - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -74,7 +72,7 @@ protected override Task FixAllAsync( } } - return Task.CompletedTask; + return; // Local function static void RemoveStatement(SyntaxEditor editor, SyntaxNode statement) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnusedLocalFunction/CSharpRemoveUnusedLocalFunctionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnusedLocalFunction/CSharpRemoveUnusedLocalFunctionCodeFixProvider.cs index 427d2f54205b2..44b394122ab9d 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnusedLocalFunction/CSharpRemoveUnusedLocalFunctionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnusedLocalFunction/CSharpRemoveUnusedLocalFunctionCodeFixProvider.cs @@ -28,13 +28,12 @@ internal sealed class CSharpRemoveUnusedLocalFunctionCodeFixProvider() : SyntaxE public sealed override ImmutableArray FixableDiagnosticIds => [CS8321]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpCodeFixesResources.Remove_unused_function, nameof(CSharpCodeFixesResources.Remove_unused_function)); - return Task.CompletedTask; } - protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; @@ -51,7 +50,5 @@ protected override Task FixAllAsync(Document document, ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.SimplifyLinqTypeCheckAndCastDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Simplify_LINQ_expression, nameof(AnalyzersResources.Simplify_LINQ_expression)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -75,7 +74,5 @@ protected override Task FixAllAsync( // Snip out the `.Where(...)` portion so that `expr.Where(...).OfType()` becomes `expr.OfType()` editor.ReplaceNode(whereInvocation, whereMemberAccess.Expression); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/SimplifyPropertyAccessor/CSharpSimplifyPropertyAccessorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/SimplifyPropertyAccessor/CSharpSimplifyPropertyAccessorCodeFixProvider.cs index e52ed94b96f79..01bdce215f0b5 100644 --- a/src/Analyzers/CSharp/CodeFixes/SimplifyPropertyAccessor/CSharpSimplifyPropertyAccessorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/SimplifyPropertyAccessor/CSharpSimplifyPropertyAccessorCodeFixProvider.cs @@ -28,13 +28,12 @@ internal sealed class CSharpSimplifyPropertyAccessorCodeFixProvider() : SyntaxEd public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.SimplifyPropertyAccessorDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Simplify_property_accessor, nameof(CSharpAnalyzersResources.Simplify_property_accessor)); - return Task.CompletedTask; } - protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { using var _ = PooledHashSet.GetInstance(out var seenPartialProperties); @@ -68,7 +67,5 @@ protected override Task FixAllAsync(Document document, ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.SimplifyPropertyPatternDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Simplify_property_pattern, nameof(CSharpAnalyzersResources.Simplify_property_pattern)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -56,8 +55,6 @@ protected override Task FixAllAsync( return simplified ?? currentSubpattern; }); } - - return Task.CompletedTask; } private static SubpatternSyntax? TrySimplify(SubpatternSyntax currentSubpattern) diff --git a/src/Analyzers/CSharp/CodeFixes/TransposeRecordKeyword/CSharpTransposeRecordKeywordCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/TransposeRecordKeyword/CSharpTransposeRecordKeywordCodeFixProvider.cs index b9294d8b975de..48fd0a3b07481 100644 --- a/src/Analyzers/CSharp/CodeFixes/TransposeRecordKeyword/CSharpTransposeRecordKeywordCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/TransposeRecordKeyword/CSharpTransposeRecordKeywordCodeFixProvider.cs @@ -78,7 +78,7 @@ private static bool TryGetTokens( return false; } - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; @@ -88,11 +88,9 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpCodeFixesResources.Fix_record_declaration, nameof(CSharpCodeFixesResources.Fix_record_declaration)); } - - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -114,7 +112,5 @@ protected override Task FixAllAsync( }); } } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UpdateProjectToAllowUnsafe/CSharpUpdateProjectToAllowUnsafeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UpdateProjectToAllowUnsafe/CSharpUpdateProjectToAllowUnsafeCodeFixProvider.cs index 3151c2fcc7490..ff8287b43bda6 100644 --- a/src/Analyzers/CSharp/CodeFixes/UpdateProjectToAllowUnsafe/CSharpUpdateProjectToAllowUnsafeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UpdateProjectToAllowUnsafe/CSharpUpdateProjectToAllowUnsafeCodeFixProvider.cs @@ -28,11 +28,10 @@ internal sealed class CSharpUpdateProjectToAllowUnsafeCodeFixProvider() : CodeFi return null; } - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(ProjectOptionsChangeAction.Create(CSharpCodeFixesResources.Allow_unsafe_code_in_this_project, - _ => Task.FromResult(AllowUnsafeOnProject(context.Document.Project))), context.Diagnostics); - return Task.CompletedTask; + async _ => AllowUnsafeOnProject(context.Document.Project)), context.Diagnostics); } private static Solution AllowUnsafeOnProject(Project project) diff --git a/src/Analyzers/CSharp/CodeFixes/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs index f6efc25c5c38a..cb7830781b485 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs @@ -77,7 +77,7 @@ protected override PropertyDeclarationSyntax RewriteFieldReferencesInProperty( return (PropertyDeclarationSyntax)rewriter.Visit(property); } - protected override Task UpdatePropertyAsync( + protected override async Task UpdatePropertyAsync( Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, @@ -105,7 +105,7 @@ protected override Task UpdatePropertyAsync( // Nothing to actually do. We're not changing the accessors to `get;set;` accessors, and we didn't have to // add an setter. We also had no field initializer to move over. This can happen when we're converting to // using `field` and that rewrite already happened. - return Task.FromResult(propertyDeclaration); + return propertyDeclaration; } // 1. If we have a trivial getters/setter then we want to convert to an accessor list to have `get;set;` @@ -140,7 +140,7 @@ protected override Task UpdatePropertyAsync( var finalProperty = updatedProperty .WithTrailingTrivia(propertyDeclaration.GetTrailingTrivia()) .WithAdditionalAnnotations(SpecializedFormattingAnnotation); - return Task.FromResult(finalProperty); + return finalProperty; static PropertyDeclarationSyntax MoveAttributes( PropertyDeclarationSyntax property, diff --git a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyCodeFixProvider.cs index be93c2fc486f8..0eaf179f1f5f5 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyCodeFixProvider.cs @@ -30,7 +30,7 @@ internal sealed partial class CSharpUseCollectionExpressionForEmptyCodeFixProvid public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseCollectionExpressionForEmptyDiagnosticId]; - protected override Task FixAsync( + protected override async Task FixAsync( Document document, SyntaxEditor editor, SyntaxNode diagnosticNode, @@ -40,6 +40,5 @@ protected override Task FixAsync( editor.ReplaceNode( diagnosticNode, (current, _) => s_emptyCollection.WithTriviaFrom(current)); - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs index a9ec9d8f034e8..ebfcc25be18c7 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs @@ -31,10 +31,9 @@ internal sealed class CSharpUseCompoundCoalesceAssignmentCodeFixProvider() : Syn public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseCoalesceCompoundAssignmentDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_compound_assignment, nameof(AnalyzersResources.Use_compound_assignment)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs index a7420b3863e3a..f031ce7ecb7d6 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs @@ -28,10 +28,9 @@ internal sealed class CSharpUseDeconstructionCodeFixProvider() : SyntaxEditorBas public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseDeconstructionDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Deconstruct_variable_declaration, nameof(CSharpAnalyzersResources.Deconstruct_variable_declaration)); - return Task.CompletedTask; } protected override Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs index 880a706cd682c..9002fd6727194 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs @@ -25,10 +25,9 @@ internal sealed partial class CSharpUseDefaultLiteralCodeFixProvider() : SyntaxE public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseDefaultLiteralDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Simplify_default_expression, nameof(CSharpAnalyzersResources.Simplify_default_expression)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs index f7546f54ed3a2..a75749b19ef3d 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs @@ -36,7 +36,7 @@ protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.IsSuppressed || diagnostic.Properties.ContainsKey(UseExpressionBodyDiagnosticAnalyzer.FixesError); - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); @@ -47,7 +47,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) var title = diagnostic.GetMessage(); RegisterCodeFix(context, title, title, priority); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs index cd77173715f61..ddfa9a6186316 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs @@ -37,10 +37,9 @@ public override ImmutableArray FixableDiagnosticIds protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.IsSuppressed; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_new, nameof(CSharpAnalyzersResources.Use_new)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs index 96db15d5bd13d..1e67d7e427ede 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs @@ -34,13 +34,12 @@ internal sealed class UseExplicitTypeCodeFixProvider() : SyntaxEditorBasedCodeFi public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseExplicitTypeDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix( context, CSharpAnalyzersResources.Use_explicit_type_instead_of_var, context.Diagnostics.First().Properties[CSharpTypeStyleUtilities.EquivalenceyKey]!); - return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string? equivalenceKey, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs index 8de161fe7de4c..1344e83810207 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs @@ -25,19 +25,18 @@ internal sealed class UseImplicitTypeCodeFixProvider() : SyntaxEditorBasedCodeFi public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseImplicitTypeDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix( context, CSharpAnalyzersResources.use_var_instead_of_explicit_type, context.Diagnostics.First().Properties[CSharpTypeStyleUtilities.EquivalenceyKey]!); - return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string? equivalenceKey, CancellationToken cancellationToken) => diagnostic.Properties[CSharpTypeStyleUtilities.EquivalenceyKey] == equivalenceKey; - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -48,8 +47,6 @@ protected override Task FixAllAsync( var typeSyntax = (TypeSyntax)root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); ReplaceTypeWithVar(editor, typeSyntax); } - - return Task.CompletedTask; } internal static void ReplaceTypeWithVar(SyntaxEditor editor, TypeSyntax type) diff --git a/src/Analyzers/CSharp/CodeFixes/UseImplicitlyTypedLambdaExpression/CSharpUseImplicitObjectCreationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseImplicitlyTypedLambdaExpression/CSharpUseImplicitObjectCreationCodeFixProvider.cs index c7e1193eedf8b..6837260355098 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseImplicitlyTypedLambdaExpression/CSharpUseImplicitObjectCreationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseImplicitlyTypedLambdaExpression/CSharpUseImplicitObjectCreationCodeFixProvider.cs @@ -30,10 +30,9 @@ internal sealed class CSharpUseImplicitlyTypedLambdaExpressionCodeFixProvider() public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseImplicitlyTypedLambdaExpressionDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_implicitly_typed_lambda, nameof(CSharpAnalyzersResources.Use_implicitly_typed_lambda)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseIndexOperatorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseIndexOperatorCodeFixProvider.cs index 01b8a9424b779..e9d3aa908d4de 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseIndexOperatorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseIndexOperatorCodeFixProvider.cs @@ -26,13 +26,12 @@ internal sealed class CSharpUseIndexOperatorCodeFixProvider() : SyntaxEditorBase public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseIndexOperatorDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_index_operator, nameof(CSharpAnalyzersResources.Use_index_operator)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -45,7 +44,5 @@ protected override Task FixAllAsync( node, (currentNode, _) => IndexExpression(((BinaryExpressionSyntax)currentNode).Right)); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseRangeOperatorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseRangeOperatorCodeFixProvider.cs index 555091f418c3c..277800dcddeda 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseRangeOperatorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseRangeOperatorCodeFixProvider.cs @@ -36,10 +36,9 @@ internal sealed class CSharpUseRangeOperatorCodeFixProvider() : SyntaxEditorBase public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseRangeOperatorDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_range_operator, nameof(CSharpAnalyzersResources.Use_range_operator)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseInterpolatedVerbatimString/CSharpUseInterpolatedVerbatimStringCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseInterpolatedVerbatimString/CSharpUseInterpolatedVerbatimStringCodeFixProvider.cs index a099c36cde8f4..a7da9bfd3a529 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseInterpolatedVerbatimString/CSharpUseInterpolatedVerbatimStringCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseInterpolatedVerbatimString/CSharpUseInterpolatedVerbatimStringCodeFixProvider.cs @@ -26,13 +26,12 @@ internal sealed partial class CSharpUseInterpolatedVerbatimStringCodeFixProvider private const string InterpolatedVerbatimText = "$@\""; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpCodeFixesResources.Use_interpolated_verbatim_string, nameof(CSharpCodeFixesResources.Use_interpolated_verbatim_string)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -41,8 +40,6 @@ protected override Task FixAllAsync( cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, diagnostic, cancellationToken); } - - return Task.CompletedTask; } private static void AddEdits( diff --git a/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs index e9d06f96ab129..1990f6ded9988 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs @@ -33,7 +33,7 @@ public override ImmutableArray FixableDiagnosticIds private static bool IsSupportedDiagnostic(Diagnostic diagnostic) => diagnostic.Properties[UseIsNullConstants.Kind] == UseIsNullConstants.CastAndEqualityKey; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); if (IsSupportedDiagnostic(diagnostic)) @@ -43,11 +43,9 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) RegisterCodeFix(context, title, title); } - - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -62,8 +60,6 @@ protected override Task FixAllAsync( binary, (current, g) => Rewrite((BinaryExpressionSyntax)current)); } - - return Task.CompletedTask; } private static ExpressionSyntax Rewrite(BinaryExpressionSyntax binary) diff --git a/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckCodeFixProvider.cs index 6b3a01664eb5f..aee7dee18239c 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckCodeFixProvider.cs @@ -28,13 +28,12 @@ internal sealed class CSharpUseNullCheckOverTypeCheckCodeFixProvider() : SyntaxE public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseNullCheckOverTypeCheckDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Prefer_null_check_over_type_check, nameof(CSharpAnalyzersResources.Prefer_null_check_over_type_check)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -56,7 +55,5 @@ protected override Task FixAllAsync( editor.ReplaceNode(node, replacement.WithTriviaFrom(node)); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs index 968fc5a76882a..74ceb2260804d 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs @@ -43,10 +43,9 @@ public override ImmutableArray FixableDiagnosticIds protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.IsSuppressed; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_local_function, nameof(CSharpAnalyzersResources.Use_local_function)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseNameofInAttribute/CSharpUseNameofInAttributeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseNameofInAttribute/CSharpUseNameofInAttributeCodeFixProvider.cs index 59059f826e54d..13fb02d51e49b 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseNameofInAttribute/CSharpUseNameofInAttributeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseNameofInAttribute/CSharpUseNameofInAttributeCodeFixProvider.cs @@ -23,16 +23,15 @@ internal sealed class CSharpUseNameofInAttributeCodeFixProvider() : SyntaxEditor { public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseNameofInAttributeDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix( context, CSharpAnalyzersResources.Use_nameof, nameof(CSharpAnalyzersResources.Use_nameof)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -48,7 +47,5 @@ protected override Task FixAllAsync( expression, editor.Generator.NameOfExpression(editor.Generator.IdentifierName(name)).WithTriviaFrom(expression)); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternCombinators/CSharpUsePatternCombinatorsCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternCombinators/CSharpUsePatternCombinatorsCodeFixProvider.cs index d16b47757308d..3b5064ff79125 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternCombinators/CSharpUsePatternCombinatorsCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternCombinators/CSharpUsePatternCombinatorsCodeFixProvider.cs @@ -55,7 +55,7 @@ protected override bool IncludeDiagnosticDuringFixAll( return isSafe == (equivalenceKey == SafeEquivalenceKey); } - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var isSafe = CSharpUsePatternCombinatorsDiagnosticAnalyzer.IsSafe(diagnostic); @@ -65,8 +65,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) isSafe ? CSharpAnalyzersResources.Use_pattern_matching : CSharpAnalyzersResources.Use_pattern_matching_may_change_code_meaning, isSafe ? SafeEquivalenceKey : UnsafeEquivalenceKey, CodeActionPriority.Low); - - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndMemberAccessCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndMemberAccessCodeFixProvider.cs index 6d46376acf94d..359fa58c3382f 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndMemberAccessCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndMemberAccessCodeFixProvider.cs @@ -30,20 +30,17 @@ internal sealed partial class CSharpAsAndMemberAccessCodeFixProvider() : SyntaxE public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UsePatternMatchingAsAndMemberAccessDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_pattern_matching, nameof(CSharpAnalyzersResources.Use_pattern_matching)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start)) FixOne(editor, diagnostic, cancellationToken); - - return Task.CompletedTask; } private static void FixOne(SyntaxEditor editor, Diagnostic diagnostic, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs index c46ae30e09d37..3ff3aeed98e00 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs @@ -30,10 +30,9 @@ internal sealed partial class CSharpAsAndNullCheckCodeFixProvider() : SyntaxEdit public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.InlineAsTypeCheckId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_pattern_matching, nameof(CSharpAnalyzersResources.Use_pattern_matching)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpIsAndCastCheckCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpIsAndCastCheckCodeFixProvider.cs index d234b3148fd34..f9ba72ad7b190 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpIsAndCastCheckCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpIsAndCastCheckCodeFixProvider.cs @@ -27,13 +27,12 @@ internal sealed partial class CSharpIsAndCastCheckCodeFixProvider() : SyntaxEdit public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.InlineIsTypeCheckId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_pattern_matching, nameof(CSharpAnalyzersResources.Use_pattern_matching)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -42,8 +41,6 @@ protected override Task FixAllAsync( cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, diagnostic, cancellationToken); } - - return Task.CompletedTask; } private static void AddEdits( diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpUseNotPatternCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpUseNotPatternCodeFixProvider.cs index 1a3f54bbdcb20..6818cd55b0ec9 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpUseNotPatternCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpUseNotPatternCodeFixProvider.cs @@ -25,10 +25,9 @@ internal sealed class CSharpUseNotPatternCodeFixProvider() : SyntaxEditorBasedCo public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseNotPatternDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_pattern_matching, nameof(CSharpAnalyzersResources.Use_pattern_matching)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs index c496dfd59323a..8d5d1e6283c79 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs @@ -53,7 +53,7 @@ public override ImmutableArray FixableDiagnosticIds => new CSharpUsePrimaryConstructorFixAllProvider(); #endif - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var document = context.Document; @@ -88,8 +88,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) diagnostic); } } - - return Task.CompletedTask; } private static async Task UsePrimaryConstructorAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseSimpleUsingStatement/UseSimpleUsingStatementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseSimpleUsingStatement/UseSimpleUsingStatementCodeFixProvider.cs index 038b093530b9c..ebee946519d5d 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseSimpleUsingStatement/UseSimpleUsingStatementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseSimpleUsingStatement/UseSimpleUsingStatementCodeFixProvider.cs @@ -34,13 +34,12 @@ internal sealed class UseSimpleUsingStatementCodeFixProvider() : SyntaxEditorBas public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseSimpleUsingStatementDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_simple_using_statement, nameof(CSharpAnalyzersResources.Use_simple_using_statement)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -56,8 +55,6 @@ protected override Task FixAllAsync( (original, current) => RewriteBlock(original, current, topmostUsingStatements)); editor.ReplaceNode(root, updatedRoot); - - return Task.CompletedTask; } private static SyntaxNode RewriteBlock( diff --git a/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockCodeFixProvider.cs index 4f1d7464f385c..339636b12d5c4 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockCodeFixProvider.cs @@ -37,7 +37,7 @@ internal sealed partial class CSharpUseSystemThreadingLockCodeFixProvider() : Co #endif - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var document = context.Document; @@ -54,8 +54,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) nameof(CSharpAnalyzersResources.Use_primary_constructor)), diagnostic); } - - return Task.CompletedTask; } private static async Task UseSystemThreadingLockAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseThrowExpression/UseThrowExpressionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseThrowExpression/UseThrowExpressionCodeFixProvider.cs index 598b1cdca3762..0b4d255c22335 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseThrowExpression/UseThrowExpressionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseThrowExpression/UseThrowExpressionCodeFixProvider.cs @@ -30,13 +30,12 @@ public override ImmutableArray FixableDiagnosticIds protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_throw_expression, nameof(AnalyzersResources.Use_throw_expression)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -78,7 +77,5 @@ protected override Task FixAllAsync( } } } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseTupleSwap/CSharpUseTupleSwapCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseTupleSwap/CSharpUseTupleSwapCodeFixProvider.cs index deff3bf44e9f2..fcd3ff922cb9a 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseTupleSwap/CSharpUseTupleSwapCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseTupleSwap/CSharpUseTupleSwapCodeFixProvider.cs @@ -27,20 +27,17 @@ internal sealed partial class CSharpUseTupleSwapCodeFixProvider() : SyntaxEditor public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseTupleSwapDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_tuple_to_swap_values, nameof(CSharpAnalyzersResources.Use_tuple_to_swap_values)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) FixOne(editor, diagnostic, cancellationToken); - - return Task.CompletedTask; } private static void FixOne( diff --git a/src/Analyzers/CSharp/CodeFixes/UseUnboundGenericTypeInNameOf/CSharpUseUnboundGenericTypeInNameOfCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseUnboundGenericTypeInNameOf/CSharpUseUnboundGenericTypeInNameOfCodeFixProvider.cs index 61565a07875fc..09c1d415413d4 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseUnboundGenericTypeInNameOf/CSharpUseUnboundGenericTypeInNameOfCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseUnboundGenericTypeInNameOf/CSharpUseUnboundGenericTypeInNameOfCodeFixProvider.cs @@ -30,20 +30,17 @@ internal sealed partial class CSharpUseUnboundGenericTypeInNameOfCodeFixProvider public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseUnboundGenericTypeInNameOfDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_unbound_generic_type, nameof(CSharpAnalyzersResources.Use_unbound_generic_type)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) FixOne(editor, diagnostic, cancellationToken); - - return Task.CompletedTask; } private static void FixOne( diff --git a/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs index 2e505e0fffed8..a7643443ae778 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs @@ -33,10 +33,9 @@ internal sealed class UseUtf8StringLiteralCodeFixProvider() : SyntaxEditorBasedC public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseUtf8StringLiteralDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_Utf8_string_literal, nameof(CSharpAnalyzersResources.Use_Utf8_string_literal)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs index 048011d9bf94b..7be88decf6ec1 100644 --- a/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs @@ -21,7 +21,7 @@ internal abstract class AbstractAddOrRemoveAccessibilityModifiersCodeFixProvider public sealed override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.AddOrRemoveAccessibilityModifiersDiagnosticId]; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); @@ -34,8 +34,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) : (AnalyzersResources.Remove_accessibility_modifiers, nameof(AnalyzersResources.Remove_accessibility_modifiers)); RegisterCodeFix(context, title, key, priority); - - return Task.CompletedTask; } protected sealed override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs index d1d7eebefb81a..b015865197eac 100644 --- a/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs @@ -93,11 +93,11 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) actions.Add(CodeAction.Create( title, - cancellationToken => + async cancellationToken => { var (finalTarget, replacement) = ApplyFix(document, semanticModel, targetNode, conversionType, cancellationToken); - return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(finalTarget, replacement))); + return document.WithSyntaxRoot(root.ReplaceNode(finalTarget, replacement)); }, title)); diff --git a/src/Analyzers/Core/CodeFixes/AddRequiredParentheses/AddRequiredParenthesesCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AddRequiredParentheses/AddRequiredParenthesesCodeFixProvider.cs index 02183781df90d..945189bfa33b5 100644 --- a/src/Analyzers/Core/CodeFixes/AddRequiredParentheses/AddRequiredParenthesesCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AddRequiredParentheses/AddRequiredParenthesesCodeFixProvider.cs @@ -27,14 +27,13 @@ protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Doc => diagnostic.Properties.ContainsKey(AddRequiredParenthesesConstants.IncludeInFixAll) && diagnostic.Properties[AddRequiredParenthesesConstants.EquivalenceKey] == equivalenceKey; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix( context, AnalyzersResources.Add_parentheses_for_clarity, context.Diagnostics[0].Properties[AddRequiredParenthesesConstants.EquivalenceKey]!); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -51,7 +50,5 @@ protected override Task FixAllAsync( (current, _) => generator.AddParentheses( current, includeElasticTrivia: false, addSimplifierAnnotation: false)); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs index 25db71024c464..6b465f0cd097c 100644 --- a/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs @@ -56,11 +56,11 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) actions.Add(CodeAction.Create( title, - cancellationToken => + async cancellationToken => { var aliasDirective = syntaxGenerator.AliasImportDeclaration(typeName, symbol); var newRoot = addImportService.AddImport(semanticModel, root, diagnosticNode, aliasDirective, syntaxGenerator, placementOption, cancellationToken); - return Task.FromResult(document.WithSyntaxRoot(newRoot)); + return document.WithSyntaxRoot(newRoot); }, title)); } diff --git a/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs index 9bf189a0dcdf0..744602ebb1c6d 100644 --- a/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs @@ -61,7 +61,7 @@ private static bool TryGetNode( var title = await GetDescriptionAsync(diagnostic, node, semanticModel, cancellationToken).ConfigureAwait(false); return CodeAction.Create( title, - token => Task.FromResult(otherDocument.WithSyntaxRoot(newRoot)), + async token => otherDocument.WithSyntaxRoot(newRoot), title); } } diff --git a/src/Analyzers/Core/CodeFixes/ConvertTypeOfToNameOf/AbstractConvertTypeOfToNameOfCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/ConvertTypeOfToNameOf/AbstractConvertTypeOfToNameOfCodeFixProvider.cs index 8dd9ef89348a6..ad7752ceff8bf 100644 --- a/src/Analyzers/Core/CodeFixes/ConvertTypeOfToNameOf/AbstractConvertTypeOfToNameOfCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/ConvertTypeOfToNameOf/AbstractConvertTypeOfToNameOfCodeFixProvider.cs @@ -24,11 +24,10 @@ internal abstract class AbstractConvertTypeOfToNameOfCodeFixProvider< public sealed override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConvertTypeOfToNameOfDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var title = GetCodeFixTitle(); RegisterCodeFix(context, title, title); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs index 07605e3783cdf..cb67623808adf 100644 --- a/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs @@ -27,7 +27,7 @@ internal abstract class AbstractFileHeaderCodeFixProvider : CodeFixProvider public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.FileHeaderMismatch]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -38,8 +38,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) nameof(AbstractFileHeaderCodeFixProvider)), diagnostic); } - - return Task.CompletedTask; } private async Task GetTransformedDocumentAsync(Document document, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs index db699f6212104..1e1cdebd44e31 100644 --- a/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs @@ -24,14 +24,12 @@ internal abstract class AbstractForEachCastCodeFixProvider FixableDiagnosticIds => [IDEDiagnosticIds.ForEachCastDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Diagnostics.First().Properties.ContainsKey(ForEachCastHelpers.IsFixable)) { RegisterCodeFix(context, AnalyzersResources.Add_explicit_cast, nameof(AbstractForEachCastCodeFixProvider<>)); } - - return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) diff --git a/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs index 04c840a6d90f1..4614e063cf9c7 100644 --- a/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs @@ -46,7 +46,7 @@ public sealed override ImmutableArray FixableDiagnosticIds protected override CodeActionRequestPriority ComputeRequestPriority() => CodeActionRequestPriority.High; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -63,8 +63,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) context.RegisterCodeFix(codeAction, diagnostic); } - - return Task.CompletedTask; } private async Task FixOneAsync(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateConversionService.State.cs b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateConversionService.State.cs index 959c63b9c913e..e980fed0db02e 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateConversionService.State.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateConversionService.State.cs @@ -30,7 +30,7 @@ public static async Task GenerateConversionStateAsync( return state; } - private Task TryInitializeConversionAsync( + private async ValueTask TryInitializeConversionAsync( TService service, SemanticDocument document, SyntaxNode node, @@ -40,18 +40,18 @@ private Task TryInitializeConversionAsync( { if (!TryInitializeImplicitConversion(service, document, node, cancellationToken)) { - return SpecializedTasks.False; + return false; } } else if (service.IsExplicitConversionGeneration(node)) { if (!TryInitializeExplicitConversion(service, document, node, cancellationToken)) { - return SpecializedTasks.False; + return false; } } - return TryFinishInitializingStateAsync(service, document, cancellationToken); + return await TryFinishInitializingStateAsync(service, document, cancellationToken).ConfigureAwait(false); } private bool TryInitializeExplicitConversion(TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs index 5e252f1496c75..b4f213ae211fe 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs @@ -37,7 +37,7 @@ public static async Task GenerateMethodStateAsync( return state; } - private Task TryInitializeMethodAsync( + private async Task TryInitializeMethodAsync( TService service, SemanticDocument document, SyntaxNode node, @@ -62,18 +62,18 @@ private Task TryInitializeMethodAsync( { if (!TryInitializeExplicitInterface(service, document, node, cancellationToken)) { - return SpecializedTasks.False; + return false; } } else if (service.IsSimpleNameGeneration(node)) { if (!TryInitializeSimpleName(service, document, (TSimpleNameSyntax)node, cancellationToken)) { - return SpecializedTasks.False; + return false; } } - return TryFinishInitializingStateAsync(service, document, cancellationToken); + return await TryFinishInitializingStateAsync(service, document, cancellationToken).ConfigureAwait(false); } private bool TryInitializeExplicitInterface( diff --git a/src/Analyzers/Core/CodeFixes/MakeFieldReadonly/AbstractMakeFieldReadonlyCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MakeFieldReadonly/AbstractMakeFieldReadonlyCodeFixProvider.cs index 092139a4ba4a8..13f70eaefdd2e 100644 --- a/src/Analyzers/Core/CodeFixes/MakeFieldReadonly/AbstractMakeFieldReadonlyCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MakeFieldReadonly/AbstractMakeFieldReadonlyCodeFixProvider.cs @@ -28,10 +28,9 @@ public override ImmutableArray FixableDiagnosticIds protected abstract SyntaxNode? GetInitializerNode(TSymbolSyntax declaration); protected abstract ImmutableList GetVariableDeclarators(TFieldDeclarationSyntax declaration); - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Add_readonly_modifier, nameof(AnalyzersResources.Add_readonly_modifier)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/MakeMemberStatic/AbstractMakeMemberStaticCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MakeMemberStatic/AbstractMakeMemberStaticCodeFixProvider.cs index 4dfca14b6c208..8d32d65b4ed11 100644 --- a/src/Analyzers/Core/CodeFixes/MakeMemberStatic/AbstractMakeMemberStaticCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MakeMemberStatic/AbstractMakeMemberStaticCodeFixProvider.cs @@ -16,18 +16,16 @@ internal abstract class AbstractMakeMemberStaticCodeFixProvider : SyntaxEditorBa { protected abstract bool TryGetMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? memberDeclaration); - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Diagnostics.Length == 1 && TryGetMemberDeclaration(context.Diagnostics[0].Location.FindNode(context.CancellationToken), out _)) { RegisterCodeFix(context, CodeFixesResources.Make_member_static, nameof(AbstractMakeMemberStaticCodeFixProvider)); } - - return Task.CompletedTask; } - protected sealed override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, + protected sealed override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { for (var i = 0; i < diagnostics.Length; i++) @@ -41,7 +39,5 @@ protected sealed override Task FixAllAsync(Document document, ImmutableArray WellKnownFixAllProviders.BatchFixer; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var diagnostic = context.Diagnostics.First(); @@ -42,8 +42,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) nameof(CodeFixesResources.Make_method_synchronous)), context.Diagnostics); } - - return Task.CompletedTask; } private const string AsyncSuffix = "Async"; diff --git a/src/Analyzers/Core/CodeFixes/MakeTypeAbstract/AbstractMakeTypeAbstractCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MakeTypeAbstract/AbstractMakeTypeAbstractCodeFixProvider.cs index 024c04392cf5e..d7be70bac2f24 100644 --- a/src/Analyzers/Core/CodeFixes/MakeTypeAbstract/AbstractMakeTypeAbstractCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MakeTypeAbstract/AbstractMakeTypeAbstractCodeFixProvider.cs @@ -17,17 +17,15 @@ internal abstract class AbstractMakeTypeAbstractCodeFixProvider diagnostics, SyntaxEditor editor, + protected sealed override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { for (var i = 0; i < diagnostics.Length; i++) @@ -38,7 +36,5 @@ protected sealed override Task FixAllAsync(Document document, ImmutableArray generator.WithModifiers(currentTypeDeclaration, generator.GetModifiers(currentTypeDeclaration).WithIsAbstract(true))); } } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/MakeTypePartial/AbstractMakeTypePartialCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MakeTypePartial/AbstractMakeTypePartialCodeFixProvider.cs index 7460dff1673ce..a89eb9789ddf7 100644 --- a/src/Analyzers/Core/CodeFixes/MakeTypePartial/AbstractMakeTypePartialCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MakeTypePartial/AbstractMakeTypePartialCodeFixProvider.cs @@ -15,10 +15,9 @@ namespace Microsoft.CodeAnalysis.MakeTypePartial; internal abstract class AbstractMakeTypePartialCodeFixProvider() : SyntaxEditorBasedCodeFixProvider(supportsFixAll: false) { - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CodeFixesResources.Make_type_partial, nameof(CodeFixesResources.Make_type_partial)); - return Task.CompletedTask; } protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs index 25f7c018648d6..ce45c5066c963 100644 --- a/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs @@ -22,7 +22,7 @@ internal abstract partial class AbstractChangeNamespaceToMatchFolderCodeFixProvi { public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var service = context.Document.Project.Solution.Services.GetRequiredService(); if (service.CanApplyChange(ApplyChangesKind.ChangeDocumentInfo)) @@ -35,8 +35,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) nameof(AnalyzersResources.Change_namespace_to_match_folder_structure)), context.Diagnostics); } - - return Task.CompletedTask; } private static async Task FixAllInDocumentAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs index b79c4bc2147e8..25cb8536c45b7 100644 --- a/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs @@ -26,7 +26,7 @@ internal sealed class ConsecutiveStatementPlacementCodeFixProvider() : CodeFixPr public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConsecutiveStatementPlacementDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -35,7 +35,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, diagnostic, c), nameof(CodeFixesResources.Add_blank_line_after_block)), context.Diagnostics); - return Task.CompletedTask; } private static Task UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesCodeFixProvider.cs index 282b5aac5e27b..009bcf10ff16a 100644 --- a/src/Analyzers/Core/CodeFixes/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesCodeFixProvider.cs @@ -26,7 +26,7 @@ internal sealed class MultipleBlankLinesCodeFixProvider() : CodeFixProvider public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.MultipleBlankLinesDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -35,7 +35,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, diagnostic, c), nameof(CodeFixesResources.Remove_extra_blank_lines)), context.Diagnostics); - return Task.CompletedTask; } private static Task UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs index a39f26bbbfa16..e671cfe1c1a79 100644 --- a/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs @@ -47,7 +47,7 @@ protected abstract void FixOneDiagnostic( bool hasMissingCases, bool hasMissingDefaultCase, TSwitchSyntax switchNode, TSwitchOperation switchOperation); - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var properties = diagnostic.Properties; @@ -92,8 +92,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) nameof(CodeFixesResources.Add_both)), context.Diagnostics); } - - return Task.CompletedTask; } private Task FixAsync( diff --git a/src/Analyzers/Core/CodeFixes/QualifyMemberAccess/AbstractQualifyMemberAccessCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/QualifyMemberAccess/AbstractQualifyMemberAccessCodeFixProvider.cs index 1c7d70e0c4d0e..0cd18c1d0d76a 100644 --- a/src/Analyzers/Core/CodeFixes/QualifyMemberAccess/AbstractQualifyMemberAccessCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/QualifyMemberAccess/AbstractQualifyMemberAccessCodeFixProvider.cs @@ -23,14 +23,13 @@ internal abstract class AbstractQualifyMemberAccessCodeFixprovider FixableDiagnosticIds => [IDEDiagnosticIds.AddThisOrMeQualificationDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var title = GetTitle(); RegisterCodeFix(context, title, title); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -50,7 +49,5 @@ protected override Task FixAllAsync( editor.ReplaceNode(node, qualifiedAccess); } } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs index 61d48f8bc0827..6cbe099f21e0e 100644 --- a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs @@ -27,7 +27,7 @@ public sealed override ImmutableArray FixableDiagnosticIds protected override CodeActionCleanup Cleanup => CodeActionCleanup.None; #endif - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var title = GetTitle(); context.RegisterCodeFix( @@ -39,7 +39,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) // code action is preferred over virtually any others that could be located at that position. priority: CodeActionPriority.High), context.Diagnostics); - return Task.CompletedTask; } private static Task RemoveUnnecessaryImportsAsync( diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesCodeFixProvider.cs index 41407b1e686b0..f36c23625649e 100644 --- a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesCodeFixProvider.cs @@ -23,10 +23,9 @@ public override ImmutableArray FixableDiagnosticIds protected abstract bool CanRemoveParentheses( TParenthesizedExpressionSyntax current, SemanticModel semanticModel, CancellationToken cancellationToken); - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Remove_unnecessary_parentheses, nameof(AnalyzersResources.Remove_unnecessary_parentheses)); - return Task.CompletedTask; } protected override Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsCodeFixProvider.cs index df44ed978de39..93c9143116fea 100644 --- a/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsCodeFixProvider.cs @@ -36,14 +36,12 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } } - protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { var node = editor.OriginalRoot.FindNode(diagnostic.Location.SourceSpan); editor.RemoveNode(node); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryPragmaSuppressionsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryPragmaSuppressionsCodeFixProvider.cs index fcb86a7ac9f86..20cb1e704ca96 100644 --- a/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryPragmaSuppressionsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryPragmaSuppressionsCodeFixProvider.cs @@ -42,7 +42,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } } - protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // We need to track unique set of processed nodes when removing the nodes. // This is because we generate an unnecessary pragma suppression diagnostic at both the pragma disable and matching pragma restore location @@ -61,7 +61,7 @@ protected override Task FixAllAsync(Document document, ImmutableArray FixableDiagnosticIds /// protected abstract void AdjustAndAddAppropriateDeclaratorsToRemove(HashSet fieldDeclarators, HashSet declarators); - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Remove_unused_member, nameof(AnalyzersResources.Remove_unused_member)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/SimplifyBooleanExpression/SimplifyConditionalCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/SimplifyBooleanExpression/SimplifyConditionalCodeFixProvider.cs index 129a02507c1e6..50ed0e34b3dd9 100644 --- a/src/Analyzers/Core/CodeFixes/SimplifyBooleanExpression/SimplifyConditionalCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/SimplifyBooleanExpression/SimplifyConditionalCodeFixProvider.cs @@ -26,10 +26,9 @@ internal sealed class SimplifyConditionalCodeFixProvider() : SyntaxEditorBasedCo public sealed override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.SimplifyConditionalExpressionDiagnosticId]; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Simplify_conditional_expression, nameof(AnalyzersResources.Simplify_conditional_expression)); - return Task.CompletedTask; } protected sealed override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs index 88f5603c5e898..15b585fce129d 100644 --- a/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs @@ -37,10 +37,9 @@ internal abstract class AbstractSimplifyInterpolationCodeFixProvider< protected abstract TInterpolationSyntax WithFormatClause(TInterpolationSyntax interpolation, TInterpolationFormatClause? formatClause); protected abstract string Escape(TInterpolatedStringExpressionSyntax interpolatedString, string formatString); - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Simplify_interpolation, nameof(AnalyzersResources.Simplify_interpolation)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/SimplifyLinqExpression/SimplifyLinqExpressionCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/SimplifyLinqExpression/SimplifyLinqExpressionCodeFixProvider.cs index d75e75c4921c7..07223b269cd8c 100644 --- a/src/Analyzers/Core/CodeFixes/SimplifyLinqExpression/SimplifyLinqExpressionCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/SimplifyLinqExpression/SimplifyLinqExpressionCodeFixProvider.cs @@ -24,13 +24,12 @@ internal sealed class SimplifyLinqExpressionCodeFixProvider() : SyntaxEditorBase public sealed override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.SimplifyLinqExpressionDiagnosticId]; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Simplify_LINQ_expression, nameof(AnalyzersResources.Simplify_LINQ_expression)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -66,7 +65,5 @@ protected override Task FixAllAsync( return innerInvocationExpression.ReplaceNode(innerName, outerName.WithTriviaFrom(innerName)).WithTrailingTrivia(current.GetTrailingTrivia()); }); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/UpdateLegacySuppressions/UpdateLegacySuppressionsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UpdateLegacySuppressions/UpdateLegacySuppressionsCodeFixProvider.cs index 1770445ee3502..9501336e1a081 100644 --- a/src/Analyzers/Core/CodeFixes/UpdateLegacySuppressions/UpdateLegacySuppressionsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UpdateLegacySuppressions/UpdateLegacySuppressionsCodeFixProvider.cs @@ -37,7 +37,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } } - protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { @@ -45,7 +45,5 @@ protected override Task FixAllAsync(Document document, ImmutableArray GetUpgradeProjectCodeActions(CodeFixContext context) @@ -56,7 +55,7 @@ protected ImmutableArray GetUpgradeProjectCodeActions(CodeFixContext var fixOneProjectTitle = string.Format(UpgradeThisProjectResource, newVersion); var fixOneProject = ProjectOptionsChangeAction.Create(fixOneProjectTitle, - _ => Task.FromResult(UpgradeProject(project, newVersion))); + async _ => UpgradeProject(project, newVersion)); result.Add(fixOneProject); @@ -65,7 +64,7 @@ protected ImmutableArray GetUpgradeProjectCodeActions(CodeFixContext var fixAllProjectsTitle = string.Format(UpgradeAllProjectsResource, newVersion); var fixAllProjects = ProjectOptionsChangeAction.Create(fixAllProjectsTitle, - ct => Task.FromResult(UpgradeAllProjects(solution, language, newVersion, ct))); + async ct => UpgradeAllProjects(solution, language, newVersion, ct)); result.Add(fixAllProjects); } @@ -111,8 +110,8 @@ private ProjectOptionsChangeAction(string title, Func> createChangedSolution) => new(title, createChangedSolution); - protected override Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) - => SpecializedTasks.EmptyEnumerable(); + protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) + => []; protected override async Task GetChangedSolutionAsync(CancellationToken cancellationToken) => await _createChangedSolution(cancellationToken).ConfigureAwait(false); @@ -132,8 +131,8 @@ private ProjectOptionsChangeAction(string title, Func, CancellationToken, Task> createChangedSolution) => new(title, createChangedSolution); - protected override Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) - => SpecializedTasks.EmptyEnumerable(); + protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) + => []; } #endif diff --git a/src/Analyzers/Core/CodeFixes/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs index 0ed1c2ac62ce2..9fe40519093af 100644 --- a/src/Analyzers/Core/CodeFixes/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs @@ -80,7 +80,7 @@ protected abstract Task UpdatePropertyAsync( bool isTrivialSetAccessor, CancellationToken cancellationToken); - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var solution = context.Document.Project.Solution; @@ -97,8 +97,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) priority), diagnostic); } - - return Task.CompletedTask; } private async Task ProcessResultAsync( diff --git a/src/Analyzers/Core/CodeFixes/UseAutoProperty/UseAutoPropertyFixAllProvider.cs b/src/Analyzers/Core/CodeFixes/UseAutoProperty/UseAutoPropertyFixAllProvider.cs index 092e4c68cef62..5fd4cf91167d8 100644 --- a/src/Analyzers/Core/CodeFixes/UseAutoProperty/UseAutoPropertyFixAllProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseAutoProperty/UseAutoPropertyFixAllProvider.cs @@ -27,11 +27,11 @@ private sealed class UseAutoPropertyFixAllProvider(TProvider provider) : FixAllP { #if CODE_STYLE - public override Task GetFixAsync(FixAllContext fixAllContext) + public override async Task GetFixAsync(FixAllContext fixAllContext) { - return Task.FromResult(CodeAction.Create( + return CodeAction.Create( fixAllContext.GetDefaultFixAllTitle(), - cancellationToken => FixAllAsync(fixAllContext, cancellationToken))); + cancellationToken => FixAllAsync(fixAllContext, cancellationToken)); } private async Task FixAllAsync(FixAllContext fixAllContext, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/AbstractUseCoalesceExpressionForIfNullStatementCheckCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/AbstractUseCoalesceExpressionForIfNullStatementCheckCodeFixProvider.cs index 6c11e4cfffccb..af540d7bf7a1e 100644 --- a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/AbstractUseCoalesceExpressionForIfNullStatementCheckCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/AbstractUseCoalesceExpressionForIfNullStatementCheckCodeFixProvider.cs @@ -18,10 +18,9 @@ internal abstract class AbstractUseCoalesceExpressionForIfNullStatementCheckCode public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseCoalesceExpressionForIfNullCheckDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_coalesce_expression, nameof(AnalyzersResources.Use_coalesce_expression)); - return Task.CompletedTask; } protected virtual ITypeSymbol? TryGetExplicitCast( diff --git a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckCodeFixProvider.cs index 3e3a0eecc8621..27e935b36a486 100644 --- a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckCodeFixProvider.cs @@ -27,10 +27,9 @@ public override ImmutableArray FixableDiagnosticIds protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_coalesce_expression, nameof(AnalyzersResources.Use_coalesce_expression)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckCodeFixProvider.cs index 2334bc175a664..301cf4f60f597 100644 --- a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckCodeFixProvider.cs @@ -28,10 +28,9 @@ public override ImmutableArray FixableDiagnosticIds protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_coalesce_expression, nameof(AnalyzersResources.Use_coalesce_expression)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/UseCompoundAssignment/AbstractUseCompoundAssignmentCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseCompoundAssignment/AbstractUseCompoundAssignmentCodeFixProvider.cs index a5ae0ef3a13e9..d66b0fdb0b127 100644 --- a/src/Analyzers/Core/CodeFixes/UseCompoundAssignment/AbstractUseCompoundAssignmentCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseCompoundAssignment/AbstractUseCompoundAssignmentCodeFixProvider.cs @@ -41,13 +41,12 @@ protected abstract TAssignmentSyntax Assignment( protected abstract TExpressionSyntax Decrement(TExpressionSyntax left, bool postfix); protected abstract SyntaxTriviaList PrepareRightExpressionLeadingTrivia(SyntaxTriviaList initialTrivia); - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_compound_assignment, nameof(AnalyzersResources.Use_compound_assignment)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -91,8 +90,6 @@ protected override Task FixAllAsync( (TExpressionSyntax)rightExpr); }); } - - return Task.CompletedTask; } protected virtual bool PreferPostfix(ISyntaxFactsService syntaxFacts, TAssignmentSyntax currentAssignment) diff --git a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs index 5d492d9355e9b..9280a7d13e982 100644 --- a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs @@ -40,14 +40,13 @@ internal abstract class AbstractUseConditionalExpressionForAssignmentCodeFixProv public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseConditionalExpressionForAssignmentDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var (title, key) = context.Diagnostics.First().Properties.ContainsKey(UseConditionalExpressionHelpers.CanSimplifyName) ? (AnalyzersResources.Simplify_check, nameof(AnalyzersResources.Simplify_check)) : (AnalyzersResources.Convert_to_conditional_expression, nameof(AnalyzersResources.Convert_to_conditional_expression)); RegisterCodeFix(context, title, key); - return Task.CompletedTask; } /// diff --git a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs index 3d1cc7843dd7b..1f0f55239374f 100644 --- a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs @@ -31,14 +31,13 @@ internal abstract class AbstractUseConditionalExpressionForReturnCodeFixProvider public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseConditionalExpressionForReturnDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var (title, key) = context.Diagnostics.First().Properties.ContainsKey(UseConditionalExpressionHelpers.CanSimplifyName) ? (AnalyzersResources.Simplify_check, nameof(AnalyzersResources.Simplify_check)) : (AnalyzersResources.Convert_to_conditional_expression, nameof(AnalyzersResources.Convert_to_conditional_expression)); RegisterCodeFix(context, title, key); - return Task.CompletedTask; } protected override async Task FixOneAsync( diff --git a/src/Analyzers/Core/CodeFixes/UseExplicitTupleName/UseExplicitTupleNameCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseExplicitTupleName/UseExplicitTupleNameCodeFixProvider.cs index 6d57a354baa1b..8379ee12addf7 100644 --- a/src/Analyzers/Core/CodeFixes/UseExplicitTupleName/UseExplicitTupleNameCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseExplicitTupleName/UseExplicitTupleNameCodeFixProvider.cs @@ -23,13 +23,12 @@ internal sealed partial class UseExplicitTupleNameCodeFixProvider() : SyntaxEdit public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseExplicitTupleNameDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_explicitly_provided_tuple_name, nameof(AnalyzersResources.Use_explicitly_provided_tuple_name)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -47,7 +46,5 @@ protected override Task FixAllAsync( editor.ReplaceNode(oldNameNode, newNameNode); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs index 8d95c70a6f730..dd6c9b0a273bd 100644 --- a/src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs @@ -18,13 +18,12 @@ internal abstract class AbstractUseInferredMemberNameCodeFixProvider : SyntaxEdi public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseInferredMemberNameDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_inferred_member_name, nameof(AnalyzersResources.Use_inferred_member_name)); - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -35,7 +34,5 @@ protected override Task FixAllAsync( var node = root.FindNode(diagnostic.Location.SourceSpan); LanguageSpecificRemoveSuggestedNode(editor, node); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsCodeFixProvider.cs index 5ccde3abcabc1..6bbcb601ed4b3 100644 --- a/src/Analyzers/Core/CodeFixes/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsCodeFixProvider.cs @@ -31,7 +31,7 @@ public override ImmutableArray FixableDiagnosticIds private static bool IsSupportedDiagnostic(Diagnostic diagnostic) => diagnostic.Properties[UseIsNullConstants.Kind] == UseIsNullConstants.ReferenceEqualsKey; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); if (IsSupportedDiagnostic(diagnostic)) @@ -40,11 +40,9 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) var title = GetTitle(negated, diagnostic.Location.SourceTree!.Options); RegisterCodeFix(context, title, title); } - - return Task.CompletedTask; } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -76,7 +74,5 @@ protected override Task FixAllAsync( toReplace, replacement.WithTriviaFrom(toReplace)); } - - return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs index 9ddd4ddfb27f0..53a7aaf02ec19 100644 --- a/src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs @@ -25,10 +25,9 @@ internal sealed class UseSystemHashCodeCodeFixProvider() : SyntaxEditorBasedCode public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseSystemHashCode]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_System_HashCode, nameof(AnalyzersResources.Use_System_HashCode)); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/EditorFeatures/CSharp/EndConstruct/CSharpEndConstructGenerationService.cs b/src/EditorFeatures/CSharp/EndConstruct/CSharpEndConstructGenerationService.cs index ce65cec44f0f4..d4b0e304231d0 100644 --- a/src/EditorFeatures/CSharp/EndConstruct/CSharpEndConstructGenerationService.cs +++ b/src/EditorFeatures/CSharp/EndConstruct/CSharpEndConstructGenerationService.cs @@ -21,6 +21,6 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.EndConstructGeneration; [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class CSharpEndConstructGenerationService() : IEndConstructGenerationService { - public Task TryDoAsync(ITextView textView, ITextBuffer subjectBuffer, char typedChar, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task TryDoAsync(ITextView textView, ITextBuffer subjectBuffer, char typedChar, CancellationToken cancellationToken) + => false; } diff --git a/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs b/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs index fd247d02858f6..b81b4b633dcde 100644 --- a/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs +++ b/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs @@ -73,7 +73,7 @@ public bool SupportsFormattingOnTypedCharacter(Document document, char ch) return s_supportedChars.IndexOf(ch) >= 0; } - public Task> GetFormattingChangesAsync( + public async Task> GetFormattingChangesAsync( Document document, ITextBuffer textBuffer, TextSpan? textSpan, @@ -85,21 +85,21 @@ public Task> GetFormattingChangesAsync( var span = textSpan ?? new TextSpan(0, parsedDocument.Root.FullSpan.Length); var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(parsedDocument.Root, span); - return Task.FromResult(Formatter.GetFormattedTextChanges(parsedDocument.Root, [formattingSpan], document.Project.Solution.Services, options, cancellationToken).ToImmutableArray()); + return Formatter.GetFormattedTextChanges(parsedDocument.Root, [formattingSpan], document.Project.Solution.Services, options, cancellationToken).ToImmutableArray(); } - public Task> GetFormattingChangesOnPasteAsync(Document document, ITextBuffer textBuffer, TextSpan textSpan, CancellationToken cancellationToken) + public async Task> GetFormattingChangesOnPasteAsync(Document document, ITextBuffer textBuffer, TextSpan textSpan, CancellationToken cancellationToken) { var parsedDocument = ParsedDocument.CreateSynchronously(document, cancellationToken); var options = textBuffer.GetSyntaxFormattingOptions(_editorOptionsService, document.Project.GetFallbackAnalyzerOptions(), parsedDocument.LanguageServices, explicitFormat: true); var service = parsedDocument.LanguageServices.GetRequiredService(); - return Task.FromResult(service.GetFormattingChangesOnPaste(parsedDocument, textSpan, options, cancellationToken)); + return service.GetFormattingChangesOnPaste(parsedDocument, textSpan, options, cancellationToken); } - public Task> GetFormattingChangesOnReturnAsync(Document document, int caretPosition, CancellationToken cancellationToken) - => SpecializedTasks.EmptyImmutableArray(); + public async Task> GetFormattingChangesOnReturnAsync(Document document, int caretPosition, CancellationToken cancellationToken) + => []; - public Task> GetFormattingChangesAsync(Document document, ITextBuffer textBuffer, char typedChar, int position, CancellationToken cancellationToken) + public async Task> GetFormattingChangesAsync(Document document, ITextBuffer textBuffer, char typedChar, int position, CancellationToken cancellationToken) { var parsedDocument = ParsedDocument.CreateSynchronously(document, cancellationToken); var service = parsedDocument.LanguageServices.GetRequiredService(); @@ -107,9 +107,9 @@ public Task> GetFormattingChangesAsync(Document docum if (service.ShouldFormatOnTypedCharacter(parsedDocument, typedChar, position, cancellationToken)) { var indentationOptions = textBuffer.GetIndentationOptions(_editorOptionsService, document.Project.GetFallbackAnalyzerOptions(), parsedDocument.LanguageServices, explicitFormat: false); - return Task.FromResult(service.GetFormattingChangesOnTypedCharacter(parsedDocument, position, indentationOptions, cancellationToken)); + return service.GetFormattingChangesOnTypedCharacter(parsedDocument, position, indentationOptions, cancellationToken); } - return SpecializedTasks.EmptyImmutableArray(); + return []; } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingNuGetTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingNuGetTests.cs index eef6fe5e746ba..286adec7ccaf1 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingNuGetTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingNuGetTests.cs @@ -62,7 +62,7 @@ public async Task TestSearchPackageCustomFeedName() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); + .Returns(async () => ImmutableArray.Empty); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -99,7 +99,7 @@ public async Task TestSearchPackageFakeNugetFeed() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); + .Returns(async () => ImmutableArray.Empty); packageServiceMock.Setup(s => s.FindPackagesAsync( "nuget.org", new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -134,7 +134,7 @@ public async Task TestSearchPackageSingleName() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); + .Returns(async () => ImmutableArray.Empty); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -169,7 +169,7 @@ public async Task TestSearchPackageMultipleNames() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); + .Returns(async () => ImmutableArray.Empty); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))); @@ -202,7 +202,7 @@ public async Task TestMissingIfPackageAlreadyInstalled() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); + .Returns(async () => ImmutableArray.Empty); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))); @@ -230,7 +230,7 @@ public async Task TestOptionsOffered() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); + .Returns(async () => ImmutableArray.Empty); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))); @@ -280,7 +280,7 @@ public async Task TestInstallGetsCalledNoVersion() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); + .Returns(async () => ImmutableArray.Empty); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -318,7 +318,7 @@ public async Task TestInstallGetsCalledWithVersion() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); + .Returns(async () => ImmutableArray.Empty); packageServiceMock.Setup(s => s.FindPackagesAsync(PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -355,7 +355,7 @@ public async Task TestFailedInstallRollsBackFile() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); + .Returns(async () => ImmutableArray.Empty); packageServiceMock.Setup(s => s.FindPackagesAsync(PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -383,8 +383,8 @@ private static ValueTask> CreateSearchResult( version: null, containingNamespaceNames: containingNamespaceNames)); } - private static ValueTask> CreateSearchResult(params PackageResult[] results) - => new(ImmutableArray.Create(results)); + private static async ValueTask> CreateSearchResult(params PackageResult[] results) + => [.. results]; private static ImmutableArray CreateNameParts(params string[] parts) => [.. parts]; diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs index db111a0b9322f..2eb2efeb5e28f 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs @@ -31,11 +31,10 @@ public MyCodeRefactoringProvider(Func changeSolution) _changeSolution = changeSolution; } - public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var codeAction = new TestCodeAction(_changeSolution(context.Document.Project.Solution)); context.RegisterRefactoring(codeAction); - return Task.CompletedTask; } private sealed class TestCodeAction : CodeAction @@ -49,8 +48,8 @@ public TestCodeAction(Solution changedSolution) public override string Title => "Title"; - protected override Task GetChangedSolutionAsync(IProgress progress, CancellationToken cancellationToken) - => Task.FromResult(_changedSolution); + protected override async Task GetChangedSolutionAsync(IProgress progress, CancellationToken cancellationToken) + => _changedSolution; } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs index 690a27ad8c479..2a02bc32afa2a 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs @@ -38,7 +38,7 @@ private sealed class TestWithDialog : VerifyCS.Test public ImmutableArray MemberNames; public Action> OptionsCallback; - protected override Task CreateWorkspaceImplAsync() + protected override async Task CreateWorkspaceImplAsync() { // If we're a dialog test, then mixin our mock and initialize its values to the ones the test asked for. var workspace = new AdhocWorkspace(s_composition.GetHostServices()); @@ -47,7 +47,7 @@ protected override Task CreateWorkspaceImplAsync() service.MemberNames = MemberNames; service.OptionsCallback = OptionsCallback; - return Task.FromResult(workspace); + return workspace; } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs index d199c6cc666c3..6f2eaf92221ce 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs @@ -3436,7 +3436,7 @@ public Test( private readonly bool _testPreselection; - protected override Task CreateWorkspaceImplAsync() + protected override async Task CreateWorkspaceImplAsync() { var hostServices = s_testServices.GetHostServices(); @@ -3448,7 +3448,7 @@ protected override Task CreateWorkspaceImplAsync() testOptionsService.CreateNew = _createNew; testOptionsService.ExpectedPrecheckedMembers = _testPreselection ? _selection : []; - return Task.FromResult(workspace); + return workspace; } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/Preview/ErrorCases/ExceptionInCodeAction.cs b/src/EditorFeatures/CSharpTest/CodeActions/Preview/ErrorCases/ExceptionInCodeAction.cs index 4735afa7e4963..4c4a8e6a56543 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/Preview/ErrorCases/ExceptionInCodeAction.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/Preview/ErrorCases/ExceptionInCodeAction.cs @@ -15,10 +15,9 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ErrorC internal sealed class ExceptionInCodeAction : CodeRefactoringProvider { - public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(new ExceptionCodeAction(), context.Span); - return Task.CompletedTask; } internal sealed class ExceptionCodeAction : CodeAction diff --git a/src/EditorFeatures/CSharpTest/CodeActions/PreviewTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/PreviewTests.cs index abb67d2e918a3..33fd873760721 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/PreviewTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/PreviewTests.cs @@ -42,11 +42,10 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(EditorT private sealed class MyCodeRefactoringProvider : CodeRefactoringProvider { - public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var codeAction = new TestCodeAction(context.Document); context.RegisterRefactoring(codeAction, context.Span); - return Task.CompletedTask; } private sealed class TestCodeAction : CodeAction @@ -64,7 +63,7 @@ public override string Title } } - protected override Task GetChangedSolutionAsync( + protected override async Task GetChangedSolutionAsync( IProgress progress, CancellationToken cancellationToken) { var solution = _oldDocument.Project.Solution; @@ -83,7 +82,7 @@ protected override Task GetChangedSolutionAsync( // Change a document - This will result in IWpfTextView previews. solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, CSharpSyntaxTree.ParseText(ChangedDocumentText, cancellationToken: cancellationToken).GetRoot(cancellationToken)); - return Task.FromResult(solution); + return solution; } } } diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs index 413bd4b1f4caa..5728825f7001e 100644 --- a/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs +++ b/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs @@ -85,7 +85,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) // Disable RS0005 as this is test code and we don't need telemetry for created code action. #pragma warning disable RS0005 // Do not use generic CodeAction.Create to create CodeAction - var fix = CodeAction.Create("QualifyWithThisFix", _ => Task.FromResult(newDocument)); + var fix = CodeAction.Create("QualifyWithThisFix", async _ => newDocument); #pragma warning restore RS0005 // Do not use generic CodeAction.Create to create CodeAction context.RegisterCodeFix(fix, context.Diagnostics); diff --git a/src/EditorFeatures/CSharpTest/EventHookup/MockSuggestionService.cs b/src/EditorFeatures/CSharpTest/EventHookup/MockSuggestionService.cs index 0d7d65adc6574..71d5a8952f6af 100644 --- a/src/EditorFeatures/CSharpTest/EventHookup/MockSuggestionService.cs +++ b/src/EditorFeatures/CSharpTest/EventHookup/MockSuggestionService.cs @@ -21,10 +21,10 @@ internal sealed class MockSuggestionService() : SuggestionServiceBase { public bool WasDismissAndBlockCalled { get; private set; } - public override Task DismissAndBlockProposalsAsync(ITextView textView, ReasonForDismiss reason, CancellationToken cancellationToken) + public override async Task DismissAndBlockProposalsAsync(ITextView textView, ReasonForDismiss reason, CancellationToken cancellationToken) { WasDismissAndBlockCalled = true; - return Task.FromResult(new AsyncDisposableStub()); + return new AsyncDisposableStub(); } public override Task TryRegisterProviderAsync(SuggestionProviderBase provider, ITextView view, string name, CancellationToken cancel) diff --git a/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.TestFixers.cs b/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.TestFixers.cs index 5a21a33eee9cf..0107c0322d2d7 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.TestFixers.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.TestFixers.cs @@ -20,7 +20,7 @@ private abstract class TestThirdPartyCodeFix : CodeFixProvider { public override ImmutableArray FixableDiagnosticIds { get; } = ["HasDefaultCase"]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -42,8 +42,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) nameof(TestThirdPartyCodeFix)), diagnostic); } - - return Task.CompletedTask; } } @@ -82,10 +80,10 @@ public TestThirdPartyCodeFixModifiesSolution() private sealed class ModifySolutionFixAll : FixAllProvider { - public override Task GetFixAsync(FixAllContext fixAllContext) + public override async Task GetFixAsync(FixAllContext fixAllContext) { var solution = fixAllContext.Solution; - return Task.FromResult(CodeAction.Create( + return CodeAction.Create( "Remove default case", async cancellationToken => { @@ -115,7 +113,7 @@ private sealed class ModifySolutionFixAll : FixAllProvider Assumes.NotNull(project); return solution.AddDocument(DocumentId.CreateNewId(project.Id), "new.cs", SourceText.From("")); }, - nameof(TestThirdPartyCodeFix))); + nameof(TestThirdPartyCodeFix)); } } } @@ -132,10 +130,10 @@ private sealed class ModifySolutionFixAll : FixAllProvider public override IEnumerable GetSupportedFixAllScopes() => [FixAllScope.Project, FixAllScope.Solution, FixAllScope.Custom]; - public override Task GetFixAsync(FixAllContext fixAllContext) + public override async Task GetFixAsync(FixAllContext fixAllContext) { var solution = fixAllContext.Solution; - return Task.FromResult(CodeAction.Create( + return CodeAction.Create( "Remove default case", async cancellationToken => { @@ -165,7 +163,7 @@ public override IEnumerable GetSupportedFixAllScopes() Assumes.NotNull(project); return solution.AddDocument(DocumentId.CreateNewId(project.Id), "new.cs", SourceText.From("")); }, - nameof(TestThirdPartyCodeFix))); + nameof(TestThirdPartyCodeFix)); } } } diff --git a/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToSearcherTests.cs b/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToSearcherTests.cs index a92871a7b18c4..154d6eb5b6ecf 100644 --- a/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToSearcherTests.cs +++ b/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToSearcherTests.cs @@ -113,8 +113,8 @@ private static void SetupSearchProject( } } - private static ValueTask IsFullyLoadedAsync(bool projectSystem, bool remoteHost) - => new(projectSystem && remoteHost); + private static async ValueTask IsFullyLoadedAsync(bool projectSystem, bool remoteHost) + => projectSystem && remoteHost; [Fact] public async Task NotFullyLoadedOnlyMakesOneSearchProjectCallIfValueReturned() @@ -274,7 +274,7 @@ public async Task DoNotCrashWithoutSearchService() var results = ImmutableArray.Create(new TestNavigateToSearchResult(workspace, new TextSpan(0, 0))); var hostMock = new Mock(MockBehavior.Strict); - hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(() => new ValueTask(true)); + hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(async () => true); // Ensure that returning null for the search service doesn't crash. hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny())).Returns(() => null); @@ -322,7 +322,7 @@ public class D var results = ImmutableArray.Create(new TestNavigateToSearchResult(workspace, new TextSpan(0, 0))); var hostMock = new Mock(MockBehavior.Strict); - hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(() => new ValueTask(true)); + hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(async () => true); var searchGeneratedDocumentsAsyncCalled = false; var searchService = new MockAdvancedNavigateToSearchService @@ -386,7 +386,7 @@ void Goo3() { } """, composition: FirstActiveAndVisibleComposition); var hostMock = new Mock(MockBehavior.Strict); - hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(() => new ValueTask(true)); + hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(async () => true); var project = workspace.CurrentSolution.Projects.Single(); var searchService = project.GetRequiredLanguageService(); @@ -446,7 +446,7 @@ void Goo3() { } """, composition: FirstActiveAndVisibleComposition); var hostMock = new Mock(MockBehavior.Strict); - hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(() => new ValueTask(true)); + hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(async () => true); var project = workspace.CurrentSolution.Projects.Single(); var searchService = project.GetRequiredLanguageService(); @@ -488,12 +488,10 @@ public void ReportIncomplete() { } - public Task AddResultsAsync(ImmutableArray results, Document? activeDocument, CancellationToken cancellationToken) + public async Task AddResultsAsync(ImmutableArray results, Document? activeDocument, CancellationToken cancellationToken) { foreach (var result in results) this.Results.Add(result); - - return Task.CompletedTask; } public void ReportProgress(int current, int maximum) @@ -512,28 +510,24 @@ private sealed class MockAdvancedNavigateToSearchService : IAdvancedNavigateToSe public Action? OnSearchGeneratedDocumentsAsyncCalled { get; set; } public Action? OnSearchProjectsAsyncCalled { get; set; } - public Task SearchCachedDocumentsAsync(Solution solution, ImmutableArray projects, ImmutableArray priorityDocuments, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) + public async Task SearchCachedDocumentsAsync(Solution solution, ImmutableArray projects, ImmutableArray priorityDocuments, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) { OnSearchCachedDocumentsAsyncCalled?.Invoke(); - return Task.CompletedTask; } - public Task SearchDocumentAsync(Document document, string searchPattern, IImmutableSet kinds, Func, Task> onResultsFound, CancellationToken cancellationToken) + public async Task SearchDocumentAsync(Document document, string searchPattern, IImmutableSet kinds, Func, Task> onResultsFound, CancellationToken cancellationToken) { OnSearchDocumentsAsyncCalled?.Invoke(); - return Task.CompletedTask; } - public Task SearchGeneratedDocumentsAsync(Solution solution, ImmutableArray projects, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) + public async Task SearchGeneratedDocumentsAsync(Solution solution, ImmutableArray projects, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) { OnSearchGeneratedDocumentsAsyncCalled?.Invoke(); - return Task.CompletedTask; } - public Task SearchProjectsAsync(Solution solution, ImmutableArray projects, ImmutableArray priorityDocuments, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) + public async Task SearchProjectsAsync(Solution solution, ImmutableArray projects, ImmutableArray priorityDocuments, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) { OnSearchProjectsAsyncCalled?.Invoke(); - return Task.CompletedTask; } } diff --git a/src/EditorFeatures/CSharpTest/PdbSourceDocument/NullResultMetadataAsSourceFileProvider.cs b/src/EditorFeatures/CSharpTest/PdbSourceDocument/NullResultMetadataAsSourceFileProvider.cs index 92d85bb06302a..8f54a1c7a225b 100644 --- a/src/EditorFeatures/CSharpTest/PdbSourceDocument/NullResultMetadataAsSourceFileProvider.cs +++ b/src/EditorFeatures/CSharpTest/PdbSourceDocument/NullResultMetadataAsSourceFileProvider.cs @@ -37,9 +37,9 @@ public void CleanupGeneratedFiles(MetadataAsSourceWorkspace workspace) { } - public Task GetGeneratedFileAsync(MetadataAsSourceWorkspace metadataWorkspace, Workspace sourceWorkspace, Project sourceProject, ISymbol symbol, bool signaturesOnly, MetadataAsSourceOptions options, string tempPath, TelemetryMessage? telemetry, CancellationToken cancellationToken) + public async Task GetGeneratedFileAsync(MetadataAsSourceWorkspace metadataWorkspace, Workspace sourceWorkspace, Project sourceProject, ISymbol symbol, bool signaturesOnly, MetadataAsSourceOptions options, string tempPath, TelemetryMessage? telemetry, CancellationToken cancellationToken) { - return Task.FromResult(NullResult); + return NullResult; } public Project? MapDocument(Document document) diff --git a/src/EditorFeatures/CSharpTest/PdbSourceDocument/TestSourceLinkService.cs b/src/EditorFeatures/CSharpTest/PdbSourceDocument/TestSourceLinkService.cs index abb47df12182d..efb5c32229790 100644 --- a/src/EditorFeatures/CSharpTest/PdbSourceDocument/TestSourceLinkService.cs +++ b/src/EditorFeatures/CSharpTest/PdbSourceDocument/TestSourceLinkService.cs @@ -20,23 +20,23 @@ public TestSourceLinkService(string? pdbFilePath = null, string? sourceFilePath _sourceFilePath = sourceFilePath; } - public Task GetPdbFilePathAsync(string dllPath, PEReader peReader, bool useDefaultSymbolServers, CancellationToken cancellationToken) + public async Task GetPdbFilePathAsync(string dllPath, PEReader peReader, bool useDefaultSymbolServers, CancellationToken cancellationToken) { if (_pdbFilePath is null) { - return Task.FromResult(null); + return null; } - return Task.FromResult(new PdbFilePathResult(_pdbFilePath)); + return new PdbFilePathResult(_pdbFilePath); } - public Task GetSourceFilePathAsync(string url, string relativePath, CancellationToken cancellationToken) + public async Task GetSourceFilePathAsync(string url, string relativePath, CancellationToken cancellationToken) { if (_sourceFilePath is null) { - return Task.FromResult(null); + return null; } - return Task.FromResult(new SourceFilePathResult(_sourceFilePath)); + return new SourceFilePathResult(_sourceFilePath); } } diff --git a/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs b/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs index f292c41ea66dc..7bb330b3acbbe 100644 --- a/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs +++ b/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs @@ -57,11 +57,11 @@ public NoCompilationTaskListService() { } - public Task> GetTaskListItemsAsync(Document document, ImmutableArray descriptors, CancellationToken cancellationToken) - => Task.FromResult(ImmutableArray.Create(new TaskListItem( + public async Task> GetTaskListItemsAsync(Document document, ImmutableArray descriptors, CancellationToken cancellationToken) + => ImmutableArray.Create(new TaskListItem( descriptors.First().Priority, "Message", document.Id, Span: new FileLinePositionSpan("dummy", new LinePosition(0, 3), new LinePosition(0, 3)), - MappedSpan: new FileLinePositionSpan("dummy", new LinePosition(0, 3), new LinePosition(0, 3))))); + MappedSpan: new FileLinePositionSpan("dummy", new LinePosition(0, 3), new LinePosition(0, 3)))); } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs index 0fa116020e644..0eb1fd0fa8789 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs @@ -20,7 +20,7 @@ public sealed class DynamicKeywordRecommenderTests : RecommenderTests public DynamicKeywordRecommenderTests() { - this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); + this.RecommendKeywordsAsync = async (position, context) => _recommender.RecommendKeywords(position, context, CancellationToken.None); } [Fact] diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/KeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/KeywordRecommenderTests.cs index 0927c6073aad6..6a2b889b73ad8 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/KeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/KeywordRecommenderTests.cs @@ -50,6 +50,6 @@ protected KeywordRecommenderTests() s_recommenderMap.TryGetValue(kind, out var recommender); Assert.NotNull(recommender); - RecommendKeywordsAsync = (position, context) => Task.FromResult(recommender.GetTestAccessor().RecommendKeywords(position, context)); + RecommendKeywordsAsync = async (position, context) => recommender.GetTestAccessor().RecommendKeywords(position, context); } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs index a7bf14de2fbc1..25f9f88d95f6c 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs @@ -18,7 +18,7 @@ public abstract class NativeIntegerKeywordRecommenderTests : RecommenderTests protected NativeIntegerKeywordRecommenderTests() { - RecommendKeywordsAsync = (position, context) => Task.FromResult(Recommender.RecommendKeywords(position, context, CancellationToken.None)); + RecommendKeywordsAsync = async (position, context) => Recommender.RecommendKeywords(position, context, CancellationToken.None); } [Fact] diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs index 7ac5283b2d4e3..eb2d73f9fa0e9 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs @@ -19,7 +19,7 @@ public sealed class NotNullKeywordRecommenderTests : RecommenderTests public NotNullKeywordRecommenderTests() { - this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); + this.RecommendKeywordsAsync = async (position, context) => _recommender.RecommendKeywords(position, context, CancellationToken.None); } [Fact] diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs index fac11b89f108e..c716d86a20d77 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs @@ -17,7 +17,7 @@ public sealed class ScopedKeywordRecommenderTests : RecommenderTests public ScopedKeywordRecommenderTests() { - this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); + this.RecommendKeywordsAsync = async (position, context) => _recommender.RecommendKeywords(position, context, CancellationToken.None); } [Fact] diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs index 3d34562407077..325e8fd97efc3 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs @@ -20,7 +20,7 @@ public sealed class VarKeywordRecommenderTests : RecommenderTests public VarKeywordRecommenderTests() { - this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); + this.RecommendKeywordsAsync = async (position, context) => _recommender.RecommendKeywords(position, context, CancellationToken.None); } [Fact] diff --git a/src/EditorFeatures/Core/BraceMatching/BraceHighlightingViewTaggerProvider.cs b/src/EditorFeatures/Core/BraceMatching/BraceHighlightingViewTaggerProvider.cs index 4c1e0d851ada9..63147caddd362 100644 --- a/src/EditorFeatures/Core/BraceMatching/BraceHighlightingViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/BraceMatching/BraceHighlightingViewTaggerProvider.cs @@ -43,19 +43,19 @@ protected override ITaggerEventSource CreateEventSource(ITextView textView, ITex TaggerEventSources.OnParseOptionChanged(subjectBuffer)); } - protected override Task ProduceTagsAsync( + protected override async Task ProduceTagsAsync( TaggerContext context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition, CancellationToken cancellationToken) { var document = documentSnapshotSpan.Document; if (!caretPosition.HasValue || document == null) { - return Task.CompletedTask; + return; } var options = GlobalOptions.GetBraceMatchingOptions(document.Project.Language); - return ProduceTagsAsync( - context, document, documentSnapshotSpan.SnapshotSpan.Snapshot, caretPosition.Value, options, cancellationToken); + await ProduceTagsAsync( + context, document, documentSnapshotSpan.SnapshotSpan.Snapshot, caretPosition.Value, options, cancellationToken).ConfigureAwait(false); } internal async Task ProduceTagsAsync( diff --git a/src/EditorFeatures/Core/Classification/Syntactic/SyntacticClassificationTaggerProvider.TagComputer.cs b/src/EditorFeatures/Core/Classification/Syntactic/SyntacticClassificationTaggerProvider.TagComputer.cs index c696fe16032f4..5839be0196cb0 100644 --- a/src/EditorFeatures/Core/Classification/Syntactic/SyntacticClassificationTaggerProvider.TagComputer.cs +++ b/src/EditorFeatures/Core/Classification/Syntactic/SyntacticClassificationTaggerProvider.TagComputer.cs @@ -244,7 +244,7 @@ static ITextSnapshot GetLatest(ImmutableSegmentedList snapshots) } } - private ValueTask ComputeChangedRangeAsync( + private async ValueTask ComputeChangedRangeAsync( SolutionServices solutionServices, IClassificationService classificationService, Document currentDocument, @@ -254,20 +254,20 @@ static ITextSnapshot GetLatest(ImmutableSegmentedList snapshots) CancellationToken cancellationToken) { if (lastProcessedDocument is null) - return ValueTask.FromResult(null); + return null; if (lastProcessedRoot != null) { // If we have syntax available fast path the change computation without async or blocking. if (currentRoot is not null) - return new(classificationService.ComputeSyntacticChangeRange(solutionServices, lastProcessedRoot, currentRoot, _diffTimeout, cancellationToken)); + return classificationService.ComputeSyntacticChangeRange(solutionServices, lastProcessedRoot, currentRoot, _diffTimeout, cancellationToken); else - return ValueTask.FromResult(null); + return null; } else { // Otherwise, fall back to the language to compute the difference based on the document contents. - return classificationService.ComputeSyntacticChangeRangeAsync(lastProcessedDocument, currentDocument, _diffTimeout, cancellationToken); + return await classificationService.ComputeSyntacticChangeRangeAsync(lastProcessedDocument, currentDocument, _diffTimeout, cancellationToken).ConfigureAwait(false); } } diff --git a/src/EditorFeatures/Core/Classification/TotalClassificationTaggerProvider.cs b/src/EditorFeatures/Core/Classification/TotalClassificationTaggerProvider.cs index 87528439091fa..f47e6a4dee4f5 100644 --- a/src/EditorFeatures/Core/Classification/TotalClassificationTaggerProvider.cs +++ b/src/EditorFeatures/Core/Classification/TotalClassificationTaggerProvider.cs @@ -78,20 +78,17 @@ public override void AddTags(NormalizedSnapshotSpanCollection spans, SegmentedLi AddTagsAsync( spans, totalTags, - addSyntacticSpansAsync: static (spans, tags, arg) => + addSyntacticSpansAsync: static async (spans, tags, arg) => { arg.syntacticTagger.AddTags(spans, tags); - return Task.CompletedTask; }, - addSemanticSpansAsync: static (spans, tags, arg) => + addSemanticSpansAsync: static async (spans, tags, arg) => { arg.semanticTagger.AddTags(spans, tags); - return Task.CompletedTask; }, - addEmbeddedSpansAsync: static (spans, tags, arg) => + addEmbeddedSpansAsync: static async (spans, tags, arg) => { arg.embeddedTagger.AddTags(spans, tags); - return Task.CompletedTask; }, (syntacticTagger, semanticTagger, embeddedTagger)).VerifyCompleted(); } diff --git a/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs b/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs index ef3608d79eeea..54a8bd0f99e96 100644 --- a/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs +++ b/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs @@ -343,15 +343,13 @@ static string BuildCopilotTextForRemarks(string copilotText, string? indentText, } } - public override Task EnabledAsync(CancellationToken cancel) + public override async Task EnabledAsync(CancellationToken cancel) { _enabled = true; - return Task.CompletedTask; } - public override Task DisabledAsync(CancellationToken cancel) + public override async Task DisabledAsync(CancellationToken cancel) { _enabled = false; - return Task.CompletedTask; } } diff --git a/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs b/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs index 62fc19c40626d..94d713258b2c5 100644 --- a/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs +++ b/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs @@ -41,9 +41,8 @@ public override async Task OnAcceptedAsync(SuggestionSessionBase session, Propos Logger.Log(FunctionId.Copilot_Generate_Documentation_Accepted, logLevel: LogLevel.Information); } - public override Task OnChangeProposalAsync(SuggestionSessionBase session, ProposalBase originalProposal, ProposalBase currentProposal, bool forward, CancellationToken cancel) + public override async Task OnChangeProposalAsync(SuggestionSessionBase session, ProposalBase originalProposal, ProposalBase currentProposal, bool forward, CancellationToken cancel) { - return Task.CompletedTask; } public override async Task OnDismissedAsync(SuggestionSessionBase session, ProposalBase? originalProposal, ProposalBase? currentProposal, ReasonForDismiss reason, CancellationToken cancel) @@ -54,17 +53,15 @@ public override async Task OnDismissedAsync(SuggestionSessionBase session, Propo Logger.Log(FunctionId.Copilot_Generate_Documentation_Dismissed, logLevel: LogLevel.Information); } - public override Task OnProposalUpdatedAsync(SuggestionSessionBase session, ProposalBase? originalProposal, ProposalBase? currentProposal, ReasonForUpdate reason, VirtualSnapshotPoint caret, CompletionState? completionState, CancellationToken cancel) + public override async Task OnProposalUpdatedAsync(SuggestionSessionBase session, ProposalBase? originalProposal, ProposalBase? currentProposal, ReasonForUpdate reason, VirtualSnapshotPoint caret, CompletionState? completionState, CancellationToken cancel) { // Now that we start the Suggestion Session earlier, we will get buffer changes when the '/' is inserted and the // shell of the documentation comment. In that case, we need to make sure we have actually have a proposal to display. if (originalProposal is not null && reason.HasFlag(ReasonForUpdate.Diverged)) { Logger.Log(FunctionId.Copilot_Generate_Documentation_Diverged, logLevel: LogLevel.Information); - return session.DismissAsync(ReasonForDismiss.DismissedAfterBufferChange, cancel); + await session.DismissAsync(ReasonForDismiss.DismissedAfterBufferChange, cancel).ConfigureAwait(false); } - - return Task.CompletedTask; } /// diff --git a/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs b/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs index 43f78192c4040..50e5083e7bea7 100644 --- a/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs +++ b/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs @@ -91,10 +91,9 @@ private void UpdateProviders(WorkspaceChangeEventArgs e) return null; } - private ValueTask UpdateProvidersAsync(CancellationToken cancellationToken) + private async ValueTask UpdateProvidersAsync(CancellationToken cancellationToken) { UpdateProviders(_workspace.CurrentSolution.SolutionState); - return ValueTask.CompletedTask; } [MemberNotNull(nameof(_whitespaceProvider))] diff --git a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs index 61748691b9c3c..ccfb17bf1576c 100644 --- a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs +++ b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs @@ -31,7 +31,7 @@ public NamingStyleSettingsProvider( Update(); } - protected override Task UpdateOptionsAsync( + protected override async Task UpdateOptionsAsync( TieredAnalyzerConfigOptions options, ImmutableArray projectsInScope, CancellationToken cancellationToken) { options.GetInitialLocationAndValue(NamingStyleOptions.NamingPreferences, out var location, out var namingPreferences); @@ -41,6 +41,5 @@ protected override Task UpdateOptionsAsync( var namingStyles = namingPreferences.Rules.NamingRules.Select(namingRule => new NamingStyleSetting(namingRule, allStyles, SettingsUpdater, fileName)); AddRange(namingStyles); - return Task.CompletedTask; } } diff --git a/src/EditorFeatures/Core/Extensibility/NavigationBar/AbstractEditorNavigationBarItemService.cs b/src/EditorFeatures/Core/Extensibility/NavigationBar/AbstractEditorNavigationBarItemService.cs index cb4b407e8de55..a4a5c3edddc8c 100644 --- a/src/EditorFeatures/Core/Extensibility/NavigationBar/AbstractEditorNavigationBarItemService.cs +++ b/src/EditorFeatures/Core/Extensibility/NavigationBar/AbstractEditorNavigationBarItemService.cs @@ -67,7 +67,7 @@ protected async Task NavigateToPositionAsync(Workspace workspace, DocumentId doc } } - internal virtual Task<(DocumentId documentId, int position, int virtualSpace)> GetNavigationLocationAsync( + internal virtual async Task<(DocumentId documentId, int position, int virtualSpace)> GetNavigationLocationAsync( Document document, NavigationBarItem item, SymbolItem symbolItem, @@ -79,7 +79,7 @@ protected async Task NavigateToPositionAsync(Workspace workspace, DocumentId doc // If the item points to a location in this document, then just determine the where that span currently // is (in case recent edits have moved it) and navigate there. var navigationSpan = item.GetCurrentItemSpan(textVersion, symbolItem.Location.InDocumentInfo.Value.navigationSpan); - return Task.FromResult((document.Id, navigationSpan.Start, 0)); + return (document.Id, navigationSpan.Start, 0); } else { @@ -87,7 +87,7 @@ protected async Task NavigateToPositionAsync(Workspace workspace, DocumentId doc // computed and stored for it. Contract.ThrowIfNull(symbolItem.Location.OtherDocumentInfo); var (documentId, span) = symbolItem.Location.OtherDocumentInfo.Value; - return Task.FromResult((documentId, span.Start, 0)); + return (documentId, span.Start, 0); } } diff --git a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptEditorInlineRenameService.cs b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptEditorInlineRenameService.cs index 06748d0f67d8d..75a9977f6ce39 100644 --- a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptEditorInlineRenameService.cs +++ b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptEditorInlineRenameService.cs @@ -36,9 +36,9 @@ public bool IsEnabled } } - public Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) + public async Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) { - return Task.FromResult(ImmutableDictionary>.Empty); + return ImmutableDictionary>.Empty; } public async Task GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) diff --git a/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.FailureInlineRenameInfo.cs b/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.FailureInlineRenameInfo.cs index 7827777589572..904f5ddcd2bec 100644 --- a/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.FailureInlineRenameInfo.cs +++ b/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.FailureInlineRenameInfo.cs @@ -43,7 +43,7 @@ private sealed class FailureInlineRenameInfo(string localizedErrorMessage) : IIn public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) => null; - public Task FindRenameLocationsAsync(SymbolRenameOptions options, CancellationToken cancellationToken) => Task.FromResult(null); + public async Task FindRenameLocationsAsync(SymbolRenameOptions options, CancellationToken cancellationToken) => null; public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable changedDocumentIDs, string replacementText) => false; diff --git a/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs b/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs index 12a77bc565221..8c010d72b9675 100644 --- a/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs +++ b/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs @@ -32,9 +32,9 @@ public async Task GetRenameInfoAsync(Document document, int p _refactorNotifyServices, symbolicInfo, cancellationToken); } - public virtual Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) + public virtual async Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) { - return Task.FromResult(ImmutableDictionary>.Empty); + return ImmutableDictionary>.Empty; } /// diff --git a/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.cs b/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.cs index 730164f11e865..18c90b8010a7e 100644 --- a/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.cs +++ b/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.cs @@ -50,7 +50,7 @@ public Task> SortCompletionListAsync( throw new NotImplementedException(); } - public Task> SortCompletionItemListAsync( + public async Task> SortCompletionItemListAsync( IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken cancellationToken) @@ -73,7 +73,7 @@ public Task> SortCompletionItemListAsync( } AsyncCompletionLogger.LogItemManagerSortTicksDataPoint(stopwatch.Elapsed); - return Task.FromResult(itemList); + return itemList; } private static void SortCompletionItems(List list, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken cancellationToken) diff --git a/src/EditorFeatures/Core/Interactive/InteractiveDocumentNavigationService.cs b/src/EditorFeatures/Core/Interactive/InteractiveDocumentNavigationService.cs index 514c1b7ed4cd4..a39805990d111 100644 --- a/src/EditorFeatures/Core/Interactive/InteractiveDocumentNavigationService.cs +++ b/src/EditorFeatures/Core/Interactive/InteractiveDocumentNavigationService.cs @@ -24,8 +24,8 @@ public InteractiveDocumentNavigationService(IThreadingContext threadingContext) _threadingContext = threadingContext; } - public override Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) - => SpecializedTasks.True; + public override async Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) + => true; public override async Task GetLocationForSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) { diff --git a/src/EditorFeatures/Core/Interactive/InteractiveSession.cs b/src/EditorFeatures/Core/Interactive/InteractiveSession.cs index 9a42733794875..57bbcf8457af0 100644 --- a/src/EditorFeatures/Core/Interactive/InteractiveSession.cs +++ b/src/EditorFeatures/Core/Interactive/InteractiveSession.cs @@ -132,7 +132,7 @@ private void ProcessInitialized(InteractiveHostPlatformInfo platformInfo, Intera { Contract.ThrowIfFalse(result.InitializationResult != null); - _workQueue.AddWork(() => + _workQueue.AddWork(async () => { _workspace.ResetSolution(); @@ -153,7 +153,6 @@ private void ProcessInitialized(InteractiveHostPlatformInfo platformInfo, Intera } _pendingBuffers.Clear(); - return Task.CompletedTask; }); } @@ -163,10 +162,9 @@ private void ProcessInitialized(InteractiveHostPlatformInfo platformInfo, Intera internal void AddSubmissionProject(ITextBuffer submissionBuffer) { _workQueue.AddWork( - () => + async () => { AddSubmissionProjectNoLock(submissionBuffer, _languageInfo.LanguageName); - return Task.CompletedTask; }); } diff --git a/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs b/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs index e53cd9238b5f3..d644ebf3be5d3 100644 --- a/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs +++ b/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs @@ -200,10 +200,9 @@ public virtual async Task OnLoadedAsync() /// Signals the extension that the language server has been successfully initialized. /// /// A which completes when actions that need to be performed when the server is ready are done. - public Task OnServerInitializedAsync() + public async Task OnServerInitializedAsync() { // We don't have any tasks that need to be triggered after the server has successfully initialized. - return Task.CompletedTask; } internal async Task> CreateAsync( @@ -265,12 +264,12 @@ public virtual AbstractLanguageServer Create( public abstract ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities); - public Task OnServerInitializeFailedAsync(ILanguageClientInitializationInfo initializationState) + public async Task OnServerInitializeFailedAsync(ILanguageClientInitializationInfo initializationState) { var initializationFailureContext = new InitializationFailureContext(); initializationFailureContext.FailureMessage = string.Format(EditorFeaturesResources.Language_client_initialization_failed, Name, initializationState.StatusMessage, initializationState.InitializationException?.ToString()); - return Task.FromResult(initializationFailureContext); + return initializationFailureContext; } /// diff --git a/src/EditorFeatures/Core/NavigateTo/DefaultNavigateToLinkService.cs b/src/EditorFeatures/Core/NavigateTo/DefaultNavigateToLinkService.cs index 477ecd75ad962..8e48a08c46987 100644 --- a/src/EditorFeatures/Core/NavigateTo/DefaultNavigateToLinkService.cs +++ b/src/EditorFeatures/Core/NavigateTo/DefaultNavigateToLinkService.cs @@ -11,16 +11,11 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation; -[ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Default)] -[Shared] -internal sealed class DefaultNavigateToLinkService : INavigateToLinkService +[ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Default), Shared] +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed class DefaultNavigateToLinkService() : INavigateToLinkService { - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public DefaultNavigateToLinkService() - { - } - - public Task TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) + => false; } diff --git a/src/EditorFeatures/Core/NavigateTo/NavigateToItemProvider.Callback.cs b/src/EditorFeatures/Core/NavigateTo/NavigateToItemProvider.Callback.cs index 0631b9ec1de83..d70ee96c8309e 100644 --- a/src/EditorFeatures/Core/NavigateTo/NavigateToItemProvider.Callback.cs +++ b/src/EditorFeatures/Core/NavigateTo/NavigateToItemProvider.Callback.cs @@ -42,7 +42,7 @@ public void Done(bool isFullyLoaded) } } - public Task AddResultsAsync(ImmutableArray results, Document? activeDocument, CancellationToken cancellationToken) + public async Task AddResultsAsync(ImmutableArray results, Document? activeDocument, CancellationToken cancellationToken) { foreach (var result in results) { @@ -76,8 +76,6 @@ public Task AddResultsAsync(ImmutableArray results, Doc // gets attention and is fixed. } } - - return Task.CompletedTask; } public void ReportProgress(int current, int maximum) diff --git a/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs b/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs index ef1fcee6668af..3aaff437230fe 100644 --- a/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs +++ b/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs @@ -169,7 +169,7 @@ public bool ExecuteCommand(SortImportsCommandArgs args, CommandExecutionContext => ExecuteCommand( args, context, // Only need syntax for this operation. - (snapshot, context) => Task.FromResult(snapshot.GetOpenDocumentInCurrentContextWithChanges()), + async (snapshot, context) => snapshot.GetOpenDocumentInCurrentContextWithChanges(), async (document, cancellationToken) => { var organizeImportsService = document.GetRequiredLanguageService(); diff --git a/src/EditorFeatures/Core/Preview/SolutionPreviewItem.cs b/src/EditorFeatures/Core/Preview/SolutionPreviewItem.cs index 513627415f4b4..6fc301ad5c7fa 100644 --- a/src/EditorFeatures/Core/Preview/SolutionPreviewItem.cs +++ b/src/EditorFeatures/Core/Preview/SolutionPreviewItem.cs @@ -26,7 +26,7 @@ internal sealed class SolutionPreviewItem(ProjectId? projectId, DocumentId? docu public readonly string? Text; public SolutionPreviewItem(ProjectId? projectId, DocumentId? documentId, string text) - : this(projectId, documentId, c => Task.FromResult(text)) + : this(projectId, documentId, async c => text) { Text = text; } diff --git a/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs b/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs index bd1ea87d40c84..157a72879346f 100644 --- a/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs @@ -90,7 +90,7 @@ protected override bool TryAddSpansToTag(ITextView textViewOpt, ITextBuffer subj return true; } - protected override Task ProduceTagsAsync( + protected override async Task ProduceTagsAsync( TaggerContext context, CancellationToken cancellationToken) { // NOTE(cyrusn): Normally we'd limit ourselves to producing tags in the span we were @@ -99,7 +99,7 @@ protected override Task ProduceTagsAsync( // don't generate all the tags then the user will cycle through an incorrect subset. if (context.CaretPosition == null) { - return Task.CompletedTask; + return; } var caretPosition = context.CaretPosition.Value; @@ -108,13 +108,13 @@ protected override Task ProduceTagsAsync( var document = context.SpansToTag.FirstOrDefault(vt => vt.SnapshotSpan.Snapshot == caretPosition.Snapshot).Document; if (document == null) { - return Task.CompletedTask; + return; } // Don't produce tags if the feature is not enabled. if (!this.GlobalOptions.GetOption(ReferenceHighlightingOptionsStorage.ReferenceHighlighting, document.Project.Language)) { - return Task.CompletedTask; + return; } // See if the user is just moving their caret around in an existing tag. If so, we don't want to actually go @@ -125,12 +125,12 @@ protected override Task ProduceTagsAsync( if (onExistingTags) { context.SetSpansTagged([]); - return Task.CompletedTask; + return; } // Otherwise, we need to go produce all tags. var options = this.GlobalOptions.GetHighlightingOptions(document.Project.Language); - return ProduceTagsAsync(context, caretPosition, document, options, cancellationToken); + await ProduceTagsAsync(context, caretPosition, document, options, cancellationToken).ConfigureAwait(false); } private static async Task ProduceTagsAsync( diff --git a/src/EditorFeatures/Core/RenameTracking/RenameTrackingCodeRefactoringProvider.cs b/src/EditorFeatures/Core/RenameTracking/RenameTrackingCodeRefactoringProvider.cs index 6ed3134e062cf..77c0ef4c14569 100644 --- a/src/EditorFeatures/Core/RenameTracking/RenameTrackingCodeRefactoringProvider.cs +++ b/src/EditorFeatures/Core/RenameTracking/RenameTrackingCodeRefactoringProvider.cs @@ -32,7 +32,7 @@ public RenameTrackingCodeRefactoringProvider( this.CustomTags = this.CustomTags.Add(CodeAction.CanBeHighPriorityTag); } - public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, _) = context; @@ -41,8 +41,6 @@ public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) if (action != null) context.RegisterRefactoring(action, renameSpan); - - return Task.CompletedTask; } /// diff --git a/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs b/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs index 1c191ca0692e4..fec23333978fe 100644 --- a/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs +++ b/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs @@ -55,15 +55,15 @@ public RenameTrackingCodeAction( protected sealed override CodeActionPriority ComputePriority() => CodeActionPriority.High; - protected override Task> ComputeOperationsAsync( + protected override async Task> ComputeOperationsAsync( IProgress progress, CancellationToken cancellationToken) { // Invoked directly without previewing. if (_renameTrackingCommitter == null && !TryInitializeRenameTrackingCommitter()) - return SpecializedTasks.EmptyImmutableArray(); + return []; var committerOperation = new RenameTrackingCommitterOperation(_renameTrackingCommitter, _threadingContext); - return Task.FromResult(ImmutableArray.Create(committerOperation)); + return ImmutableArray.Create(committerOperation); } protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) diff --git a/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.WorkspaceChangedEventSource.cs b/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.WorkspaceChangedEventSource.cs index 2ecc88d76e084..016afce62688c 100644 --- a/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.WorkspaceChangedEventSource.cs +++ b/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.WorkspaceChangedEventSource.cs @@ -27,10 +27,9 @@ public WorkspaceChangedEventSource( // only process a tag change once. _asyncDelay = new AsyncBatchingWorkQueue( DelayTimeSpan.Short, - processBatchAsync: cancellationToken => + processBatchAsync: async cancellationToken => { RaiseChanged(); - return ValueTask.CompletedTask; }, asyncListener, CancellationToken.None); diff --git a/src/EditorFeatures/Core/SignatureHelp/Controller.Session_SetModelSelectedItem.cs b/src/EditorFeatures/Core/SignatureHelp/Controller.Session_SetModelSelectedItem.cs index 47ce299bf4529..9ce9cf1fe6023 100644 --- a/src/EditorFeatures/Core/SignatureHelp/Controller.Session_SetModelSelectedItem.cs +++ b/src/EditorFeatures/Core/SignatureHelp/Controller.Session_SetModelSelectedItem.cs @@ -18,7 +18,7 @@ private void SetModelExplicitlySelectedItem(Func selec this.Computation.ThreadingContext.ThrowIfNotOnUIThread(); Computation.ChainTaskAndNotifyControllerWhenFinished( - (model, cancellationToken) => Task.FromResult(SetModelExplicitlySelectedItemInBackground(model, selector)), + async (model, cancellationToken) => SetModelExplicitlySelectedItemInBackground(model, selector), updateController: false); } diff --git a/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs b/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs index e53eef6742d31..de8b96a15144a 100644 --- a/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs +++ b/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs @@ -29,10 +29,10 @@ private sealed class RefineUsingCopilotCodeAction( { public override string Title => EditorFeaturesResources.Refine_using_Copilot; - protected override Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) + protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) { // Make sure we don't trigger the refinement session for preview operation - return Task.FromResult(SpecializedCollections.EmptyEnumerable()); + return SpecializedCollections.EmptyEnumerable(); } protected override async Task> ComputeOperationsAsync(IProgress progress, CancellationToken cancellationToken) diff --git a/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedAction.cs b/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedAction.cs index 96d9164950b36..52203733b741d 100644 --- a/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedAction.cs +++ b/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedAction.cs @@ -220,13 +220,13 @@ protected async Task GetPreviewResultAsync(CancellationTo public virtual bool HasPreview => false; - public virtual Task GetPreviewAsync(CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public virtual async Task GetPreviewAsync(CancellationToken cancellationToken) + => null; public virtual bool HasActionSets => false; - public virtual Task> GetActionSetsAsync(CancellationToken cancellationToken) - => SpecializedTasks.EmptyEnumerable(); + public virtual async Task> GetActionSetsAsync(CancellationToken cancellationToken) + => []; #region not supported diff --git a/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedActionWithNestedActions.cs b/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedActionWithNestedActions.cs index feba7ae149989..4a040e7621896 100644 --- a/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedActionWithNestedActions.cs +++ b/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedActionWithNestedActions.cs @@ -34,17 +34,15 @@ internal sealed class EditorSuggestedActionWithNestedActions( public sealed override bool HasActionSets => true; - public sealed override Task> GetActionSetsAsync(CancellationToken cancellationToken) - => Task.FromResult>(NestedActionSets); + public sealed override async Task> GetActionSetsAsync(CancellationToken cancellationToken) + => NestedActionSets; - protected sealed override Task InnerInvokeAsync(IProgress progress, CancellationToken cancellationToken) + protected sealed override async Task InnerInvokeAsync(IProgress progress, CancellationToken cancellationToken) { // A code action with nested actions is itself never invokable. So just do nothing if this ever gets asked. // Report a message in debug and log a watson exception so that if this is hit we can try to narrow down how // this happened. Debug.Fail($"{nameof(InnerInvokeAsync)} should not be called on a {nameof(EditorSuggestedActionWithNestedActions)}"); FatalError.ReportAndCatch(new InvalidOperationException($"{nameof(InnerInvokeAsync)} should not be called on a {nameof(EditorSuggestedActionWithNestedActions)}"), ErrorSeverity.Critical); - - return Task.CompletedTask; } } diff --git a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs index 87237a63e2c1e..2283c07b01e8b 100644 --- a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs +++ b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs @@ -102,7 +102,7 @@ private void RemoveTagsThatIntersectEdit(TextContentChangedEventArgs e) // Everything we're passing in here is synchronous. So we can assert that this must complete synchronously // as well. var (oldTagTrees, newTagTrees, _) = CompareAndSwapTagTreesAsync( - static (oldTagTrees, args, _) => + static async (oldTagTrees, args, _) => { var (@this, e, tagsToRemove, allTagsList, allTagsSet) = args; @@ -135,12 +135,12 @@ private void RemoveTagsThatIntersectEdit(TextContentChangedEventArgs e) snapshot, @this._dataSource.SpanTrackingMode, allTagsList); - return ValueTask.FromResult((oldTagTrees.SetItem(buffer, newTagTree), default(VoidResult))); + return (oldTagTrees.SetItem(buffer, newTagTree), default(VoidResult)); } } // return oldTagTrees to indicate nothing changed. - return ValueTask.FromResult((oldTagTrees, default(VoidResult))); + return (oldTagTrees, default(VoidResult)); }, args: (this, e, tagsToRemove, allTagsList, allTagsSet), _disposalTokenSource.Token).VerifyCompleted(); diff --git a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs index 55a2e9158c3cb..59c0d10b3228f 100644 --- a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs +++ b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs @@ -41,12 +41,12 @@ private void OnTagsChangedForBuffer( } } - private ValueTask ProcessTagsChangedAsync( + private async ValueTask ProcessTagsChangedAsync( ImmutableSegmentedList snapshotSpans, CancellationToken cancellationToken) { var tagsChanged = this.TagsChanged; if (tagsChanged == null) - return ValueTask.CompletedTask; + return; foreach (var collection in snapshotSpans) { @@ -65,8 +65,6 @@ private ValueTask ProcessTagsChangedAsync( foreach (var span in coalesced) tagsChanged(this, new SnapshotSpanEventArgs(span)); } - - return ValueTask.CompletedTask; } } } diff --git a/src/EditorFeatures/Core/Workspaces/ITextBufferVisibilityTracker.cs b/src/EditorFeatures/Core/Workspaces/ITextBufferVisibilityTracker.cs index 390bed532d090..c914050bd901f 100644 --- a/src/EditorFeatures/Core/Workspaces/ITextBufferVisibilityTracker.cs +++ b/src/EditorFeatures/Core/Workspaces/ITextBufferVisibilityTracker.cs @@ -42,7 +42,7 @@ internal static class ITextBufferVisibilityTrackerExtensions /// Waits the specified amount of time while the specified is not visible. If /// any document visibility changes happen, the delay will cancel. /// - public static Task DelayWhileNonVisibleAsync( + public static async Task DelayWhileNonVisibleAsync( this ITextBufferVisibilityTracker? service, IThreadingContext threadingContext, IAsynchronousOperationListener listener, @@ -52,7 +52,7 @@ public static Task DelayWhileNonVisibleAsync( { // Only add a delay if we have access to a service that will tell us when the buffer become visible or not. if (service is null) - return Task.CompletedTask; + return; // Because cancellation is both expensive, and a super common thing to occur while we're delaying the caller // until visibility, we special case the implementation here and transition to the canceled state @@ -63,14 +63,14 @@ public static Task DelayWhileNonVisibleAsync( // it's very reasonable for the delay-task to complete synchronously (we've already been canceled, or the // buffer is already visible. So fast path that out. if (delayTask.IsCompleted) - return delayTask; + await delayTask.ConfigureAwait(false); var taskOfTask = delayTask.ContinueWith( // Convert a successfully completed task when we were canceled to a canceled task. Otherwise, return // the faulted or non-canceled task as is. task => task.Status == TaskStatus.RanToCompletion && cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : task, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - return taskOfTask.Unwrap(); + await taskOfTask.Unwrap().ConfigureAwait(false); // Normal delay logic, except that this does not throw in the event of cancellation, but instead returns // gracefully. The above task continuation logic then ensures we return a canceled task without needing diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs index 12f1018088ebb..c258a6b17a3d3 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs @@ -84,8 +84,8 @@ private static async Task GetFixAllFixAsync( return await refactorAllProvider.GetRefactoringAsync(refactorAllContext).ConfigureAwait(false); } - protected override Task> GetDiagnosticsWorkerAsync(EditorTestWorkspace workspace, TestParameters parameters) - => SpecializedTasks.EmptyImmutableArray(); + protected override async Task> GetDiagnosticsWorkerAsync(EditorTestWorkspace workspace, TestParameters parameters) + => []; internal override async Task GetCodeRefactoringAsync( EditorTestWorkspace workspace, TestParameters parameters) diff --git a/src/EditorFeatures/ExternalAccess/Debugger/GlassTestsHotReloadService.cs b/src/EditorFeatures/ExternalAccess/Debugger/GlassTestsHotReloadService.cs index 642d144e3d866..79547aee64957 100644 --- a/src/EditorFeatures/ExternalAccess/Debugger/GlassTestsHotReloadService.cs +++ b/src/EditorFeatures/ExternalAccess/Debugger/GlassTestsHotReloadService.cs @@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.Debugger; internal sealed class GlassTestsHotReloadService { private static readonly ActiveStatementSpanProvider s_noActiveStatementSpanProvider = - (_, _, _) => ValueTask.FromResult(ImmutableArray.Empty); + async (_, _, _) => ImmutableArray.Empty; private readonly IManagedHotReloadService _debuggerService; @@ -29,7 +29,7 @@ public GlassTestsHotReloadService(HostWorkspaceServices services, IManagedHotRel } #pragma warning disable IDE0060 // Remove unused parameter - public Task StartSessionAsync(Solution solution, CancellationToken cancellationToken) + public async Task StartSessionAsync(Solution solution, CancellationToken cancellationToken) #pragma warning restore IDE0060 { var newSessionId = _encService.StartDebuggingSession( @@ -40,8 +40,6 @@ public Task StartSessionAsync(Solution solution, CancellationToken cancellationT Contract.ThrowIfFalse(_sessionId == default, "Session already started"); _sessionId = newSessionId; - - return Task.CompletedTask; } private DebuggingSessionId GetSessionId() diff --git a/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs b/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs index b828c08c2ff69..bfa286dd3e922 100644 --- a/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs +++ b/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs @@ -394,7 +394,7 @@ public sealed override ImmutableArray FixableDiagnosticIds get { return [Id]; } } - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { Called = true; ContextDiagnosticsCount = context.Diagnostics.Length; @@ -403,11 +403,9 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) context.RegisterCodeFix( CodeAction.Create( _registerFixWithTitle, - createChangedDocument: _ => Task.FromResult(context.Document)), + createChangedDocument: async _ => context.Document), context.Diagnostics); } - - return Task.CompletedTask; } } @@ -556,16 +554,16 @@ public MockDocumentDiagnosticAnalyzer() public override ImmutableArray SupportedDiagnostics { get; } - public override Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) + public override async Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) { ReceivedCallback = true; - return Task.FromResult(ImmutableArray.Empty); + return ImmutableArray.Empty; } - public override Task> AnalyzeSemanticsAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) + public override async Task> AnalyzeSemanticsAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) { ReceivedCallback = true; - return Task.FromResult(ImmutableArray.Empty); + return ImmutableArray.Empty; } } @@ -781,11 +779,10 @@ protected AbstractNuGetOrVsixCodeFixProvider(ImmutableArray fixableDiagn public override ImmutableArray FixableDiagnosticIds { get; } - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var fixableDiagnostics = context.Diagnostics.WhereAsArray(d => FixableDiagnosticIds.Contains(d.Id)); - context.RegisterCodeFix(CodeAction.Create(_name, ct => Task.FromResult(context.Document)), fixableDiagnostics); - return Task.CompletedTask; + context.RegisterCodeFix(CodeAction.Create(_name, async ct => context.Document), fixableDiagnostics); } } @@ -816,13 +813,11 @@ public CodeFixProviderWithDuplicateEquivalenceKeyActions(string diagnosticId, st public override ImmutableArray FixableDiagnosticIds => [_diagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { // Register duplicate code actions with same equivalence key, but different title. RegisterCodeFix(context, titleSuffix: "1"); RegisterCodeFix(context, titleSuffix: "2"); - - return Task.CompletedTask; } private void RegisterCodeFix(CodeFixContext context, string titleSuffix) @@ -830,7 +825,7 @@ private void RegisterCodeFix(CodeFixContext context, string titleSuffix) context.RegisterCodeFix( CodeAction.Create( nameof(CodeFixProviderWithDuplicateEquivalenceKeyActions) + titleSuffix, - ct => Task.FromResult(context.Document), + async ct => context.Document, _equivalenceKey), context.Diagnostics); } @@ -909,7 +904,7 @@ protected AbstractAdditionalFileCodeFixProvider(string title) public sealed override ImmutableArray FixableDiagnosticIds => [AdditionalFileAnalyzer.DiagnosticId]; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(CodeAction.Create(Title, createChangedSolution: async ct => @@ -921,8 +916,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) }, equivalenceKey: Title), context.Diagnostics[0]); - - return Task.CompletedTask; } } @@ -1205,14 +1198,13 @@ private sealed class FixerForDeprioritizedAnalyzer : CodeFixProvider public static readonly string Title = $"Fix {DeprioritizedAnalyzer.Descriptor.Id}"; public override ImmutableArray FixableDiagnosticIds => [DeprioritizedAnalyzer.Descriptor.Id]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( CodeAction.Create(Title, - createChangedDocument: _ => Task.FromResult(context.Document), + createChangedDocument: async _ => context.Document, equivalenceKey: nameof(FixerForDeprioritizedAnalyzer)), context.Diagnostics); - return Task.CompletedTask; } } } diff --git a/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs b/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs index 9804a12d48a13..e20a39cbfda71 100644 --- a/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs +++ b/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs @@ -63,11 +63,9 @@ public TypeScriptCodeRefactoringProvider() { } - public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(CodeAction.Create($"Blocking=false", _ => Task.FromResult(null))); - - return Task.CompletedTask; } } @@ -117,14 +115,12 @@ private static async Task VerifyRefactoringDisabledAsync() internal sealed class StubRefactoring : CodeRefactoringProvider { - public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(CodeAction.Create( nameof(StubRefactoring), - cancellationToken => Task.FromResult(context.Document), + async cancellationToken => context.Document, equivalenceKey: nameof(StubRefactoring))); - - return Task.CompletedTask; } } @@ -295,7 +291,7 @@ internal abstract class AbstractNonSourceFileRefactoring : CodeRefactoringProvid protected AbstractNonSourceFileRefactoring(string title) => Title = title; - public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(CodeAction.Create(Title, createChangedSolution: async ct => @@ -307,8 +303,6 @@ public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) return document.Project.Solution.WithAdditionalDocumentText(document.Id, newText); return document.Project.Solution.WithAnalyzerConfigDocumentText(document.Id, newText); })); - - return Task.CompletedTask; } } diff --git a/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs b/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs index fc3e35d1c6a9d..243a47677dde1 100644 --- a/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs +++ b/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs @@ -116,14 +116,14 @@ public override async Task ProvideCompletionsAsync(CompletionContext context) context.CompletionListSpan = await GetTextChangeSpanAsync(context.Document, context.CompletionListSpan, context.CancellationToken).ConfigureAwait(false); } - public override Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) + public override async Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { - return Task.FromResult(CompletionDescription.FromText(nameof(DebugAssertTestCompletionProvider))); + return CompletionDescription.FromText(nameof(DebugAssertTestCompletionProvider)); } - public override Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) + public override async Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) { - return Task.FromResult(CompletionChange.Create(new TextChange(item.Span, nameof(DebugAssertTestCompletionProvider)))); + return CompletionChange.Create(new TextChange(item.Span, nameof(DebugAssertTestCompletionProvider))); } private static async Task GetTextChangeSpanAsync(Document document, TextSpan startSpan, CancellationToken cancellationToken) diff --git a/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs b/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs index 463403f829658..fd4c976a14a2e 100644 --- a/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs +++ b/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs @@ -1012,10 +1012,9 @@ private sealed class LeakDocumentAnalyzer : DocumentDiagnosticAnalyzer public override ImmutableArray SupportedDiagnostics => [s_syntaxRule]; - public override Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree tree, CancellationToken cancellationToken) + public override async Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree tree, CancellationToken cancellationToken) { - return Task.FromResult>( - [Diagnostic.Create(s_syntaxRule, tree.GetRoot(cancellationToken).GetLocation())]); + return [Diagnostic.Create(s_syntaxRule, tree.GetRoot(cancellationToken).GetLocation())]; } } diff --git a/src/EditorFeatures/Test/FindReferences/FindReferencesCommandHandlerTests.cs b/src/EditorFeatures/Test/FindReferences/FindReferencesCommandHandlerTests.cs index 3a6a31da9eb4c..fdcd9784c5594 100644 --- a/src/EditorFeatures/Test/FindReferences/FindReferencesCommandHandlerTests.cs +++ b/src/EditorFeatures/Test/FindReferences/FindReferencesCommandHandlerTests.cs @@ -30,14 +30,12 @@ private sealed class MockFindUsagesContext : FindUsagesContext { public readonly List Result = []; - public override ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) + public override async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (Result) { Result.Add(definition); } - - return default; } } diff --git a/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs b/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs index 71152e7aec433..34e57f5b49388 100644 --- a/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs +++ b/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs @@ -178,12 +178,12 @@ internal sealed class TypeScriptHandler : AbstractVSTypeScriptRequestHandler HandleRequestAsync(TSRequest request, TypeScriptRequestContext context, CancellationToken cancellationToken) + protected override async Task HandleRequestAsync(TSRequest request, TypeScriptRequestContext context, CancellationToken cancellationToken) { Assert.NotNull(context.Solution); AssertEx.NotNull(context.Document); Assert.Equal(context.Document.GetURI(), request.Document); - return Task.FromResult(Response); + return Response; } } } diff --git a/src/EditorFeatures/Test/LinkedFiles/LinkedFileDiffMergingEditorTests.cs b/src/EditorFeatures/Test/LinkedFiles/LinkedFileDiffMergingEditorTests.cs index bb3881d8e3662..da16387f07081 100644 --- a/src/EditorFeatures/Test/LinkedFiles/LinkedFileDiffMergingEditorTests.cs +++ b/src/EditorFeatures/Test/LinkedFiles/LinkedFileDiffMergingEditorTests.cs @@ -108,7 +108,7 @@ public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContex .WithDocumentText(document.Id, (await document.GetTextAsync()).Replace(textString.IndexOf("public"), "public".Length, "internal")) .WithDocumentText(linkedDocument.Id, sourceText.Replace(textString.LastIndexOf("public"), "public".Length, "private")); - context.RegisterRefactoring(CodeAction.Create("Description", _ => Task.FromResult(newSolution)), context.Span); + context.RegisterRefactoring(CodeAction.Create("Description", async _ => newSolution), context.Span); } } } diff --git a/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.cs b/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.cs index b9b19dcf47696..48effdc3bf745 100644 --- a/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.cs +++ b/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.cs @@ -23,7 +23,7 @@ public abstract partial class AbstractMetadataAsSourceTests : IAsyncLifetime { protected static readonly string ICSharpCodeDecompilerVersion = "9.1.0.7988"; - public virtual Task InitializeAsync() + public virtual async Task InitializeAsync() { AssemblyResolver.TestAccessor.AddInMemoryImage(TestBase.MscorlibRef_v46, "mscorlib.v4_6_1038_0.dll", ImmutableArray.Create(Net461.ReferenceInfos.mscorlib.ImageBytes)); AssemblyResolver.TestAccessor.AddInMemoryImage(TestBase.SystemRef_v46, "System.v4_6_1038_0.dll", ImmutableArray.Create(Net461.ReferenceInfos.System.ImageBytes)); @@ -33,15 +33,11 @@ public virtual Task InitializeAsync() AssemblyResolver.TestAccessor.AddInMemoryImage(TestBase.MsvbRef, "Microsoft.VisualBasic.dll", ImmutableArray.Create(Net461.Resources.MicrosoftVisualBasic)); AssemblyResolver.TestAccessor.AddInMemoryImage(TestBase.SystemXmlRef, "System.Xml.v4_0_30319.dll", ImmutableArray.Create(Net461.Resources.SystemXml)); AssemblyResolver.TestAccessor.AddInMemoryImage(TestBase.SystemXmlLinqRef, "System.Xml.Linq.v4_0_30319.dll", ImmutableArray.Create(Net461.Resources.SystemXmlLinq)); - - return Task.CompletedTask; } - public virtual Task DisposeAsync() + public virtual async Task DisposeAsync() { AssemblyResolver.TestAccessor.ClearInMemoryImages(); - - return Task.CompletedTask; } internal static async Task GenerateAndVerifySourceAsync( diff --git a/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs b/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs index 1c6b693d9d5f4..f535dcc81506f 100644 --- a/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs +++ b/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs @@ -259,13 +259,11 @@ protected override TaggerDelay EventChangeDelay protected override ITaggerEventSource CreateEventSource(ITextView? textView, ITextBuffer subjectBuffer) => eventSource; - protected override Task ProduceTagsAsync( + protected override async Task ProduceTagsAsync( TaggerContext context, DocumentSnapshotSpan snapshotSpan, int? caretPosition, CancellationToken cancellationToken) { foreach (var tag in callback(context, snapshotSpan)) context.AddTag(tag); - - return Task.CompletedTask; } protected override bool TagEquals(TextMarkerTag tag1, TextMarkerTag tag2) diff --git a/src/EditorFeatures/Test/UnusedReferences/UnusedReferencesRemoverTests.cs b/src/EditorFeatures/Test/UnusedReferences/UnusedReferencesRemoverTests.cs index 2fef5def6bc4f..50c85c6bd6441 100644 --- a/src/EditorFeatures/Test/UnusedReferences/UnusedReferencesRemoverTests.cs +++ b/src/EditorFeatures/Test/UnusedReferences/UnusedReferencesRemoverTests.cs @@ -213,10 +213,10 @@ public Task> GetProjectReferencesAsync(string proj throw new System.NotImplementedException(); } - public Task TryUpdateReferenceAsync(string projectPath, ReferenceUpdate referenceUpdate, CancellationToken cancellationToken) + public async Task TryUpdateReferenceAsync(string projectPath, ReferenceUpdate referenceUpdate, CancellationToken cancellationToken) { _appliedUpdates.Add(referenceUpdate); - return Task.FromResult(true); + return true; } } } diff --git a/src/EditorFeatures/TestUtilities/FindUsages/FindUsagesTestContext.cs b/src/EditorFeatures/TestUtilities/FindUsages/FindUsagesTestContext.cs index f35726022c7c6..8b12bcd43deb6 100644 --- a/src/EditorFeatures/TestUtilities/FindUsages/FindUsagesTestContext.cs +++ b/src/EditorFeatures/TestUtilities/FindUsages/FindUsagesTestContext.cs @@ -25,14 +25,12 @@ public bool ShouldShow(DefinitionItem definition) return definition.DisplayIfNoReferences; } - public override ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) + public override async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (_gate) { Definitions.Add(definition); } - - return default; } public override async ValueTask OnReferencesFoundAsync(IAsyncEnumerable references, CancellationToken cancellationToken) diff --git a/src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs b/src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs index 67ddac8523f42..0f77a07078140 100644 --- a/src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs +++ b/src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs @@ -262,7 +262,7 @@ public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] protected sealed class TestWorkspaceNavigateToSearchHostService() : IWorkspaceNavigateToSearcherHostService { - public ValueTask IsFullyLoadedAsync(CancellationToken cancellationToken) - => new(true); + public async ValueTask IsFullyLoadedAsync(CancellationToken cancellationToken) + => true; } } diff --git a/src/EditorFeatures/TestUtilities/Workspaces/NoCompilationDocumentDiagnosticAnalyzer.cs b/src/EditorFeatures/TestUtilities/Workspaces/NoCompilationDocumentDiagnosticAnalyzer.cs index 6958c6eefd15a..5ed3727438d98 100644 --- a/src/EditorFeatures/TestUtilities/Workspaces/NoCompilationDocumentDiagnosticAnalyzer.cs +++ b/src/EditorFeatures/TestUtilities/Workspaces/NoCompilationDocumentDiagnosticAnalyzer.cs @@ -20,9 +20,9 @@ internal sealed class NoCompilationDocumentDiagnosticAnalyzer : DocumentDiagnost public override ImmutableArray SupportedDiagnostics => [Descriptor]; - public override Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree tree, CancellationToken cancellationToken) + public override async Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree tree, CancellationToken cancellationToken) { - return Task.FromResult(ImmutableArray.Create( - Diagnostic.Create(Descriptor, Location.Create(document.FilePath, default, default)))); + return ImmutableArray.Create( + Diagnostic.Create(Descriptor, Location.Create(document.FilePath, default, default))); } } diff --git a/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs b/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs index 839ef19d05b14..03f545b781379 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs @@ -30,10 +30,10 @@ private RefactorAllProvider() public override IEnumerable GetSupportedRefactorAllScopes() => [RefactorAllScope.Solution]; - public override Task GetRefactoringAsync(RefactorAllContext fixAllContext) + public override async Task GetRefactoringAsync(RefactorAllContext fixAllContext) { Debug.Assert(fixAllContext.Scope == RefactorAllScope.Solution); - return Task.FromResult(new FixAllCodeAction(EnableNullableReferenceTypesInSolutionAsync)); + return new FixAllCodeAction(EnableNullableReferenceTypesInSolutionAsync); async Task EnableNullableReferenceTypesInSolutionAsync( CodeActionPurpose purpose, IProgress progress, CancellationToken cancellationToken) diff --git a/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeCodeRefactoringProvider.cs index 8567987595b96..d5bbe6f0f664c 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeCodeRefactoringProvider.cs @@ -32,9 +32,8 @@ protected override TypeSyntax FindAnalyzableType(SyntaxNode node, SemanticModel protected override TypeStyleResult AnalyzeTypeName(TypeSyntax typeName, SemanticModel semanticModel, CSharpSimplifierOptions options, CancellationToken cancellationToken) => CSharpUseImplicitTypeHelper.Instance.AnalyzeTypeName(typeName, semanticModel, options, cancellationToken); - protected override Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken) + protected override async Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken) { UseImplicitTypeCodeFixProvider.ReplaceTypeWithVar(editor, type); - return Task.CompletedTask; } } diff --git a/src/Features/CSharp/Portable/CodeRefactorings/UseRecursivePatterns/UseRecursivePatternsCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/CodeRefactorings/UseRecursivePatterns/UseRecursivePatternsCodeRefactoringProvider.cs index ca1c863dbf3ac..82627f28ab148 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/UseRecursivePatterns/UseRecursivePatternsCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/UseRecursivePatterns/UseRecursivePatternsCodeRefactoringProvider.cs @@ -65,7 +65,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte context.RegisterRefactoring( CodeAction.Create( CSharpFeaturesResources.Use_recursive_patterns, - _ => Task.FromResult(document.WithSyntaxRoot(replacementFunc(root))), + async _ => document.WithSyntaxRoot(replacementFunc(root)), nameof(CSharpFeaturesResources.Use_recursive_patterns))); } diff --git a/src/Features/CSharp/Portable/Completion/CSharpCompletionService.cs b/src/Features/CSharp/Portable/Completion/CSharpCompletionService.cs index dc1efe67c8b1b..b0507828f831c 100644 --- a/src/Features/CSharp/Portable/Completion/CSharpCompletionService.cs +++ b/src/Features/CSharp/Portable/Completion/CSharpCompletionService.cs @@ -68,7 +68,7 @@ internal override CompletionRules GetRules(CompletionOptions options) return newRules; } - internal override async Task IsSpeculativeTypeParameterContextAsync(Document document, int position, CancellationToken cancellationToken) + internal override async ValueTask IsSpeculativeTypeParameterContextAsync(Document document, int position, CancellationToken cancellationToken) { var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/AttributeNamedParameterCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/AttributeNamedParameterCompletionProvider.cs index e525d687a4d53..ebd313850f93b 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/AttributeNamedParameterCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/AttributeNamedParameterCompletionProvider.cs @@ -243,8 +243,8 @@ private static IEnumerable GetAttributeNamedParameters( return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within); } - protected override Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) - => Task.FromResult(GetTextChange(selectedItem, ch)); + protected override async Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + => GetTextChange(selectedItem, ch); private static TextChange? GetTextChange(CompletionItem selectedItem, char? ch) { diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs index 3281aeda172f5..50f65ccd6d3d3 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs @@ -365,14 +365,14 @@ private static CompletionItemRules GetRules(string displayText) } } - protected override Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + protected override async Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { if (!SymbolCompletionItem.TryGetInsertionText(selectedItem, out var insertionText)) { insertionText = selectedItem.DisplayText; } - return Task.FromResult(new TextChange(selectedItem.Span, insertionText)); + return new TextChange(selectedItem.Span, insertionText); } internal TestAccessor GetTestAccessor() diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs index 65a62f5b1d49b..e7cf6c02234cf 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs @@ -61,14 +61,14 @@ public override async Task ProvideCompletionsAsync(CompletionContext context) } } - protected override Task> GetSymbolsAsync( + protected override async Task> GetSymbolsAsync( CompletionContext? completionContext, CSharpSyntaxContext context, int position, CompletionOptions options, CancellationToken cancellationToken) { var targetToken = context.TargetToken; // Don't want to offer this after "async" (even though the compiler may parse that as a type). if (SyntaxFacts.GetContextualKeywordKind(targetToken.ValueText) == SyntaxKind.AsyncKeyword) - return SpecializedTasks.EmptyImmutableArray(); + return []; var potentialTypeNode = targetToken.Parent; if (targetToken.IsKind(SyntaxKind.GreaterThanToken) && potentialTypeNode is TypeArgumentListSyntax typeArgumentList) @@ -89,17 +89,17 @@ protected override Task> GetSymbolsAsync( } if (typeNode == null) - return SpecializedTasks.EmptyImmutableArray(); + return []; // We weren't after something that looked like a type. var tokenBeforeType = typeNode.GetFirstToken().GetPreviousToken(); if (!IsPreviousTokenValid(tokenBeforeType)) - return SpecializedTasks.EmptyImmutableArray(); + return []; var typeDeclaration = typeNode.GetAncestor(); if (typeDeclaration == null) - return SpecializedTasks.EmptyImmutableArray(); + return []; // Looks syntactically good. See what interfaces our containing class/struct/interface has Debug.Assert(IsClassOrStructOrInterfaceOrRecord(typeDeclaration)); @@ -115,7 +115,7 @@ protected override Task> GetSymbolsAsync( interfaceSet.AddRange(directInterface.AllInterfaces); } - return Task.FromResult(interfaceSet.SelectAsArray(t => new SymbolAndSelectionInfo(Symbol: t, Preselect: false))); + return interfaceSet.SelectAsArray(t => new SymbolAndSelectionInfo(Symbol: t, Preselect: false)); } private static bool IsPreviousTokenValid(SyntaxToken tokenBeforeType) diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMemberImportCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMemberImportCompletionProvider.cs index 85b8c0c52f911..e665f235033e8 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMemberImportCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMemberImportCompletionProvider.cs @@ -46,7 +46,7 @@ protected override bool IsFinalSemicolonOfUsingOrExtern(SyntaxNode directive, Sy }; } - protected override Task ShouldProvideParenthesisCompletionAsync( + protected override async Task ShouldProvideParenthesisCompletionAsync( Document document, CompletionItem item, char? commitKey, @@ -57,7 +57,7 @@ protected override Task ShouldProvideParenthesisCompletionAsync( // it can only be used as like: bar.ToInt(); // Func x = bar.ToInt or Func x = bar.ToInt is illegal. It can't be assign to delegate. // Therefore at here we always assume the user always wants to add parenthesis. - => Task.FromResult(commitKey is ';' or '.'); + => commitKey is ';' or '.'; protected override (ITypeSymbol? receiverTypeSymbol, bool isStatic) TryGetReceiverTypeSymbol( SemanticModel semanticModel, diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.cs index ea2d30a4250d0..4a423e7237ec5 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.cs @@ -277,12 +277,12 @@ bool IEqualityComparer.Equals(IParameterSymbol? x, IParameterS int IEqualityComparer.GetHashCode(IParameterSymbol obj) => obj.Name.GetHashCode(); - protected override Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + protected override async Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { - return Task.FromResult(new TextChange( + return new TextChange( selectedItem.Span, // Insert extra colon if committing with '(' only: "method(parameter:(" is preferred to "method(parameter(". // In all other cases, do not add extra colon. Note that colon is already added if committing with ':'. - ch == '(' ? selectedItem.GetEntireDisplayText() : selectedItem.DisplayText)); + ch == '(' ? selectedItem.GetEntireDisplayText() : selectedItem.DisplayText); } } diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/TupleNameCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/TupleNameCompletionProvider.cs index 9a6d275f073a8..7e8eb091f0b62 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/TupleNameCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/TupleNameCompletionProvider.cs @@ -113,11 +113,11 @@ private static void AddItems(ImmutableArray inferredTypes, int } } - protected override Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + protected override async Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { - return Task.FromResult(new TextChange( + return new TextChange( selectedItem.Span, - selectedItem.DisplayText)); + selectedItem.DisplayText); } public override ImmutableHashSet TriggerCharacters => []; diff --git a/src/Features/CSharp/Portable/Completion/Providers/DefaultArgumentProvider.cs b/src/Features/CSharp/Portable/Completion/Providers/DefaultArgumentProvider.cs index 678c1d7046b04..aed957642f6c3 100644 --- a/src/Features/CSharp/Portable/Completion/Providers/DefaultArgumentProvider.cs +++ b/src/Features/CSharp/Portable/Completion/Providers/DefaultArgumentProvider.cs @@ -22,7 +22,7 @@ public DefaultArgumentProvider() { } - public override Task ProvideArgumentAsync(ArgumentContext context) + public override async Task ProvideArgumentAsync(ArgumentContext context) { if (context.PreviousValue is { }) { @@ -52,7 +52,5 @@ public override Task ProvideArgumentAsync(ArgumentContext context) _ => "default", }; } - - return Task.CompletedTask; } } diff --git a/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs b/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs index 00cf305a680e5..1075a6e961e0b 100644 --- a/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs +++ b/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs @@ -24,18 +24,18 @@ public OutVariableArgumentProvider() { } - public override Task ProvideArgumentAsync(ArgumentContext context) + public override async Task ProvideArgumentAsync(ArgumentContext context) { if (context.PreviousValue is not null) { // This argument provider does not attempt to replace arguments already in code. - return Task.CompletedTask; + return; } if (context.Parameter.RefKind != RefKind.Out) { // This argument provider only considers 'out' parameters. - return Task.CompletedTask; + return; } // Since tihs provider runs after ContextVariableArgumentProvider, we know there is no suitable target in @@ -60,6 +60,5 @@ public override Task ProvideArgumentAsync(ArgumentContext context) [])))); context.DefaultValue = syntax.NormalizeWhitespace().ToFullString(); - return Task.CompletedTask; } } diff --git a/src/Features/CSharp/Portable/Copilot/CSharpCopilotCodeFixProvider.DismissChangesCodeAction.cs b/src/Features/CSharp/Portable/Copilot/CSharpCopilotCodeFixProvider.DismissChangesCodeAction.cs index aaee437c94516..a5beb9785fa38 100644 --- a/src/Features/CSharp/Portable/Copilot/CSharpCopilotCodeFixProvider.DismissChangesCodeAction.cs +++ b/src/Features/CSharp/Portable/Copilot/CSharpCopilotCodeFixProvider.DismissChangesCodeAction.cs @@ -22,12 +22,11 @@ private sealed class CopilotDismissChangesCodeAction(SyntaxNode originalMethodNo { public override string Title => FeaturesResources.Dismiss; - protected override Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) - => Task.FromResult>(null!); + protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) + => null!; - protected override Task> ComputeOperationsAsync(CancellationToken cancellationToken) - => Task.FromResult>( - [new TriggerDismissalCodeActionOperation(originalMethodNode, diagnostic)]); + protected override async Task> ComputeOperationsAsync(CancellationToken cancellationToken) + => [new TriggerDismissalCodeActionOperation(originalMethodNode, diagnostic)]; private sealed class TriggerDismissalCodeActionOperation(SyntaxNode originalMethodNode, Diagnostic diagnostic) : CodeActionOperation { diff --git a/src/Features/CSharp/Portable/DocumentHighlighting/CSharpDocumentHighlightsService.cs b/src/Features/CSharp/Portable/DocumentHighlighting/CSharpDocumentHighlightsService.cs index d8ff380709b28..a08bdb4e4294d 100644 --- a/src/Features/CSharp/Portable/DocumentHighlighting/CSharpDocumentHighlightsService.cs +++ b/src/Features/CSharp/Portable/DocumentHighlighting/CSharpDocumentHighlightsService.cs @@ -31,7 +31,7 @@ internal sealed class CSharpDocumentHighlightsService( CSharpSyntaxKinds.Instance, services) { - protected override async Task> GetAdditionalReferencesAsync( + protected override async ValueTask> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { // The FindRefs engine won't find references through 'var' for performance reasons. diff --git a/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs b/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs index 36b10c8df0b20..6fdd8560c3cbe 100644 --- a/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs +++ b/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs @@ -63,7 +63,7 @@ internal override bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode) return typeDeclaration.Modifiers.Any(m => SyntaxFacts.IsAccessibilityModifier(m.Kind())); } - protected override Task UpdateMembersWithExplicitImplementationsAsync( + protected override async Task UpdateMembersWithExplicitImplementationsAsync( Solution unformattedSolution, IReadOnlyList documentIds, INamedTypeSymbol extractedInterface, INamedTypeSymbol typeToExtractFrom, IEnumerable includedMembers, ImmutableDictionary symbolToDeclarationMap, @@ -72,6 +72,6 @@ protected override Task UpdateMembersWithExplicitImplementationsAsync( // In C#, member implementations do not always need // to be explicitly added. It's safe enough to return // the passed in solution - return Task.FromResult(unformattedSolution); + return unformattedSolution; } } diff --git a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs index 842a16f5c4305..ac9232df581a6 100644 --- a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs +++ b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs @@ -83,10 +83,10 @@ protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite() protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite() => this.SelectionResult.GetLastStatementUnderContainer(); - protected override Task GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken) + protected override async Task GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken) { var statement = GetStatementContainingInvocationToExtractedMethodWorker(); - return Task.FromResult(statement.WithAdditionalAnnotations(CallSiteAnnotation)); + return statement.WithAdditionalAnnotations(CallSiteAnnotation); } } } diff --git a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs index befaafb31ffc3..cadfe83c8c745 100644 --- a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs +++ b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs @@ -44,10 +44,10 @@ protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite() return this.SelectionResult.GetFirstStatement(); } - protected override Task GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken) + protected override async Task GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken) { var statement = GetStatementContainingInvocationToExtractedMethodWorker(); - return Task.FromResult(statement.WithAdditionalAnnotations(CallSiteAnnotation)); + return statement.WithAdditionalAnnotations(CallSiteAnnotation); } } } diff --git a/src/Features/CSharp/Portable/GoToDefinition/CSharpGoToDefinitionSymbolService.cs b/src/Features/CSharp/Portable/GoToDefinition/CSharpGoToDefinitionSymbolService.cs index af747c6470b09..a0b5f2f03af54 100644 --- a/src/Features/CSharp/Portable/GoToDefinition/CSharpGoToDefinitionSymbolService.cs +++ b/src/Features/CSharp/Portable/GoToDefinition/CSharpGoToDefinitionSymbolService.cs @@ -22,8 +22,8 @@ namespace Microsoft.CodeAnalysis.CSharp.GoToDefinition; [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class CSharpGoToDefinitionSymbolService() : AbstractGoToDefinitionSymbolService { - protected override Task FindRelatedExplicitlyDeclaredSymbolAsync(Project project, ISymbol symbol, CancellationToken cancellationToken) - => Task.FromResult(symbol); + protected override async Task FindRelatedExplicitlyDeclaredSymbolAsync(Project project, ISymbol symbol, CancellationToken cancellationToken) + => symbol; protected override int? GetTargetPositionIfControlFlow(SemanticModel semanticModel, SyntaxToken token) { diff --git a/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs b/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs index 3a051264177cf..e63edc15a02ab 100644 --- a/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs +++ b/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs @@ -22,7 +22,7 @@ namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable; internal sealed partial class CSharpIntroduceVariableService { - protected override Task IntroduceFieldAsync( + protected override async Task IntroduceFieldAsync( SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, @@ -68,7 +68,7 @@ protected override Task IntroduceFieldAsync( var finalTypeDeclaration = InsertMember(newTypeDeclaration, newFieldDeclaration, insertionIndex); var newRoot = document.Root.ReplaceNode(oldTypeDeclaration, finalTypeDeclaration); - return Task.FromResult(document.Document.WithSyntaxRoot(newRoot)); + return document.Document.WithSyntaxRoot(newRoot); } else { @@ -81,7 +81,7 @@ protected override Task IntroduceFieldAsync( : DetermineFieldInsertPosition(oldCompilationUnit.Members, newCompilationUnit.Members); var newRoot = newCompilationUnit.WithMembers(newCompilationUnit.Members.Insert(insertionIndex, newFieldDeclaration)); - return Task.FromResult(document.Document.WithSyntaxRoot(newRoot)); + return document.Document.WithSyntaxRoot(newRoot); } } diff --git a/src/Features/CSharp/Portable/LanguageServices/CSharpSymbolDisplayService.SymbolDescriptionBuilder.cs b/src/Features/CSharp/Portable/LanguageServices/CSharpSymbolDisplayService.SymbolDescriptionBuilder.cs index 7d26c03d7f728..71e5dd9c5b902 100644 --- a/src/Features/CSharp/Portable/LanguageServices/CSharpSymbolDisplayService.SymbolDescriptionBuilder.cs +++ b/src/Features/CSharp/Portable/LanguageServices/CSharpSymbolDisplayService.SymbolDescriptionBuilder.cs @@ -92,24 +92,24 @@ protected override void AddEnumUnderlyingTypeSeparator() Space()); } - protected override Task> GetInitializerSourcePartsAsync( + protected override async Task> GetInitializerSourcePartsAsync( ISymbol symbol) { // Actually check for C# symbol types here. if (symbol is IParameterSymbol parameter) { - return GetInitializerSourcePartsAsync(parameter); + return await GetInitializerSourcePartsAsync(parameter).ConfigureAwait(false); } else if (symbol is ILocalSymbol local) { - return GetInitializerSourcePartsAsync(local); + return await GetInitializerSourcePartsAsync(local).ConfigureAwait(false); } else if (symbol is IFieldSymbol field) { - return GetInitializerSourcePartsAsync(field); + return await GetInitializerSourcePartsAsync(field).ConfigureAwait(false); } - return SpecializedTasks.EmptyImmutableArray(); + return []; } protected override ImmutableArray ToMinimalDisplayParts(ISymbol symbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format) diff --git a/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs b/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs index c13f4d3f7e28b..eaecc0fa61d38 100644 --- a/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs +++ b/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs @@ -38,13 +38,13 @@ await GetQuickinfoForPragmaWarningAsync(document, token, cancellationToken).Conf await GetQuickInfoForSuppressMessageAttributeAsync(document, token, cancellationToken).ConfigureAwait(false); } - protected override Task BuildQuickInfoAsync( + protected override async Task BuildQuickInfoAsync( CommonQuickInfoContext context, SyntaxToken token) { // TODO: This provider currently needs access to Document/Project to compute applicable analyzers // and provide quick info, which is not available in CommonQuickInfoContext. - return Task.FromResult(null); + return null; } private static async Task GetQuickinfoForPragmaWarningAsync( diff --git a/src/Features/CSharp/Portable/QuickInfo/CSharpSyntacticQuickInfoProvider.cs b/src/Features/CSharp/Portable/QuickInfo/CSharpSyntacticQuickInfoProvider.cs index 4a8c56fd6b141..f34c4994ae03c 100644 --- a/src/Features/CSharp/Portable/QuickInfo/CSharpSyntacticQuickInfoProvider.cs +++ b/src/Features/CSharp/Portable/QuickInfo/CSharpSyntacticQuickInfoProvider.cs @@ -23,15 +23,15 @@ namespace Microsoft.CodeAnalysis.CSharp.QuickInfo; [method: SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] internal sealed class CSharpSyntacticQuickInfoProvider() : CommonQuickInfoProvider { - protected override Task BuildQuickInfoAsync( + protected override async Task BuildQuickInfoAsync( QuickInfoContext context, SyntaxToken token) - => Task.FromResult(BuildQuickInfo(token, context.CancellationToken)); + => BuildQuickInfo(token, context.CancellationToken); - protected override Task BuildQuickInfoAsync( + protected override async Task BuildQuickInfoAsync( CommonQuickInfoContext context, SyntaxToken token) - => Task.FromResult(BuildQuickInfo(token, context.CancellationToken)); + => BuildQuickInfo(token, context.CancellationToken); private static QuickInfoItem? BuildQuickInfo(SyntaxToken token, CancellationToken cancellationToken) { diff --git a/src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProviderBase_MethodGroup.cs b/src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProviderBase_MethodGroup.cs index 5b2a83eecbef4..d89891c0fd99d 100644 --- a/src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProviderBase_MethodGroup.cs +++ b/src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProviderBase_MethodGroup.cs @@ -17,7 +17,7 @@ namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp; internal abstract partial class InvocationExpressionSignatureHelpProviderBase { - internal virtual Task<(ImmutableArray items, int? selectedItemIndex)> GetMethodGroupItemsAndSelectionAsync( + internal virtual async Task<(ImmutableArray items, int? selectedItemIndex)> GetMethodGroupItemsAndSelectionAsync( ImmutableArray accessibleMethods, Document document, InvocationExpressionSyntax invocationExpression, @@ -29,7 +29,7 @@ internal abstract partial class InvocationExpressionSignatureHelpProviderBase var items = accessibleMethods.SelectAsArray(method => ConvertMethodGroupMethod( document, method, invocationExpression.SpanStart, semanticModel)); var selectedItemIndex = TryGetSelectedIndex(accessibleMethods, currentSymbol); - return Task.FromResult((items, selectedItemIndex)); + return (items, selectedItemIndex); } private static ImmutableArray GetAccessibleMethods( diff --git a/src/Features/CSharp/Portable/Snippets/AbstractCSharpAutoPropertySnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/AbstractCSharpAutoPropertySnippetProvider.cs index 3068e293019c9..dbd917f054aab 100644 --- a/src/Features/CSharp/Portable/Snippets/AbstractCSharpAutoPropertySnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/AbstractCSharpAutoPropertySnippetProvider.cs @@ -75,16 +75,16 @@ protected override async Task GenerateSnippetSyntaxAs protected override int GetTargetCaretPosition(PropertyDeclarationSyntax propertyDeclaration, SourceText sourceText) => propertyDeclaration.AccessorList!.CloseBraceToken.Span.End; - protected override ValueTask> GetPlaceHolderLocationsListAsync( + protected override async ValueTask> GetPlaceHolderLocationsListAsync( Document document, PropertyDeclarationSyntax propertyDeclaration, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { var identifier = propertyDeclaration.Identifier; var type = propertyDeclaration.Type; - return new([ + return [ new SnippetPlaceholder(type.ToString(), type.SpanStart), new SnippetPlaceholder(identifier.ValueText, identifier.SpanStart), - ]); + ]; } protected override PropertyDeclarationSyntax? FindAddedSnippetSyntaxNode(SyntaxNode root, int position) diff --git a/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs index 489b8af6abeb4..f02eacb351808 100644 --- a/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs @@ -45,14 +45,14 @@ internal abstract class AbstractCSharpForLoopSnippetProvider : AbstractForLoopSn protected override bool CanInsertStatementAfterToken(SyntaxToken token) => token.IsBeginningOfStatementContext() || token.IsBeginningOfGlobalStatementContext(); - protected override ValueTask AdjustSnippetExpressionAsync( + protected override async ValueTask AdjustSnippetExpressionAsync( Document document, ForStatementSyntax snippetExpressionNode, CancellationToken cancellationToken) { var editor = new SyntaxEditor(snippetExpressionNode, document.Project.Solution.Services); foreach (var node in snippetExpressionNode.Declaration!.DescendantNodesAndSelf().Reverse()) editor.ReplaceNode(node, (node, _) => node.WithAdditionalAnnotations(Simplifier.Annotation)); - return new((ForStatementSyntax)editor.GetChangedRoot()); + return (ForStatementSyntax)editor.GetChangedRoot(); } protected override ForStatementSyntax GenerateStatement( @@ -108,7 +108,7 @@ protected override ForStatementSyntax GenerateStatement( } } - protected override ValueTask> GetPlaceHolderLocationsListAsync( + protected override async ValueTask> GetPlaceHolderLocationsListAsync( Document document, ForStatementSyntax forStatement, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { using var _ = ArrayBuilder.GetInstance(out var result); @@ -133,7 +133,7 @@ protected override ValueTask> GetPlaceHolderL foreach (var (key, value) in placeholderBuilder) result.Add(new(key, [.. value])); - return new(result.ToImmutableAndClear()); + return result.ToImmutableAndClear(); } protected override int GetTargetCaretPosition(ForStatementSyntax forStatement, SourceText sourceText) diff --git a/src/Features/CSharp/Portable/Snippets/CSharpElseSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/CSharpElseSnippetProvider.cs index a720e79571b8d..867c740ee82fc 100644 --- a/src/Features/CSharp/Portable/Snippets/CSharpElseSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/CSharpElseSnippetProvider.cs @@ -54,10 +54,10 @@ protected override bool IsValidSnippetLocationCore(SnippetContext context, Cance return isAfterIfStatement && base.IsValidSnippetLocationCore(context, cancellationToken); } - protected override Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) + protected override async Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) { var elseClause = SyntaxFactory.ElseClause(SyntaxFactory.Block()); - return Task.FromResult(new TextChange(TextSpan.FromBounds(position, position), elseClause.ToFullString())); + return new TextChange(TextSpan.FromBounds(position, position), elseClause.ToFullString()); } protected override int GetTargetCaretPosition(ElseClauseSyntax elseClause, SourceText sourceText) diff --git a/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs index fa3e97345f88c..259a436d11a8c 100644 --- a/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs @@ -111,7 +111,7 @@ protected override ForEachStatementSyntax GenerateStatement( /// Goes through each piece of the foreach statement and extracts the identifiers /// as well as their locations to create SnippetPlaceholder's of each. /// - protected override ValueTask> GetPlaceHolderLocationsListAsync( + protected override async ValueTask> GetPlaceHolderLocationsListAsync( Document document, ForEachStatementSyntax node, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { using var _ = ArrayBuilder.GetInstance(out var arrayBuilder); @@ -120,7 +120,7 @@ protected override ValueTask> GetPlaceHolderL if (!ConstructedFromInlineExpression) arrayBuilder.Add(new SnippetPlaceholder(node.Expression.ToString(), node.Expression.SpanStart)); - return new(arrayBuilder.ToImmutableAndClear()); + return arrayBuilder.ToImmutableAndClear(); } protected override int GetTargetCaretPosition(ForEachStatementSyntax forEachStatement, SourceText sourceText) diff --git a/src/Features/CSharp/Portable/Snippets/CSharpLockSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/CSharpLockSnippetProvider.cs index 10a6b9d6620cc..eb433a3aa0ae9 100644 --- a/src/Features/CSharp/Portable/Snippets/CSharpLockSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/CSharpLockSnippetProvider.cs @@ -25,11 +25,11 @@ internal sealed class CSharpLockSnippetProvider() : AbstractLockSnippetProvider< public override string Description => CSharpFeaturesResources.lock_statement; - protected override ValueTask> GetPlaceHolderLocationsListAsync( + protected override async ValueTask> GetPlaceHolderLocationsListAsync( Document document, LockStatementSyntax node, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { var expression = node.Expression; - return new([new SnippetPlaceholder(expression.ToString(), expression.SpanStart)]); + return [new SnippetPlaceholder(expression.ToString(), expression.SpanStart)]; } protected override int GetTargetCaretPosition(LockStatementSyntax lockStatement, SourceText sourceText) diff --git a/src/Features/CSharp/Portable/Snippets/CSharpUsingSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/CSharpUsingSnippetProvider.cs index 43f6e9f7a3ee1..1cb0ae592b30c 100644 --- a/src/Features/CSharp/Portable/Snippets/CSharpUsingSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/CSharpUsingSnippetProvider.cs @@ -25,11 +25,11 @@ internal sealed class CSharpUsingSnippetProvider() : AbstractUsingSnippetProvide public override string Description => CSharpFeaturesResources.using_statement; - protected override ValueTask> GetPlaceHolderLocationsListAsync( + protected override async ValueTask> GetPlaceHolderLocationsListAsync( Document document, UsingStatementSyntax node, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { var expression = node.Expression!; - return new([new SnippetPlaceholder(expression.ToString(), expression.SpanStart)]); + return [new SnippetPlaceholder(expression.ToString(), expression.SpanStart)]; } protected override int GetTargetCaretPosition(UsingStatementSyntax usingStatement, SourceText sourceText) diff --git a/src/Features/CSharp/Portable/UsePatternMatching/CSharpIsAndCastCheckWithoutNameCodeFixProvider.cs b/src/Features/CSharp/Portable/UsePatternMatching/CSharpIsAndCastCheckWithoutNameCodeFixProvider.cs index 7c224bfc4c712..26c700c5a46a9 100644 --- a/src/Features/CSharp/Portable/UsePatternMatching/CSharpIsAndCastCheckWithoutNameCodeFixProvider.cs +++ b/src/Features/CSharp/Portable/UsePatternMatching/CSharpIsAndCastCheckWithoutNameCodeFixProvider.cs @@ -27,10 +27,9 @@ internal sealed partial class CSharpIsAndCastCheckWithoutNameCodeFixProvider() public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.InlineIsTypeWithoutNameCheckDiagnosticsId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_pattern_matching, nameof(CSharpAnalyzersResources.Use_pattern_matching), CodeActionPriority.Low); - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs b/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs index 0d937ea4b9e77..8b3718486997a 100644 --- a/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs +++ b/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs @@ -568,7 +568,7 @@ private sealed class CustomCompositionCSharpTest : VerifyCS.Test private TestWorkspace? _testWorkspace; private Action? _copilotServiceSetupAction; - protected override Task CreateWorkspaceImplAsync() + protected override async Task CreateWorkspaceImplAsync() { _testComposition = FeaturesTestCompositions.Features .AddParts([typeof(TestCopilotOptionsService), typeof(TestCopilotCodeAnalysisService)]); @@ -576,7 +576,7 @@ protected override Task CreateWorkspaceImplAsync() // Trigger the action if it's set _copilotServiceSetupAction?.Invoke(GetCopilotService(_testWorkspace)); - return Task.FromResult(_testWorkspace); + return _testWorkspace; } public CustomCompositionCSharpTest WithMockCopilotService(Action setup) @@ -608,20 +608,20 @@ private sealed class TestCopilotOptionsService : ICopilotOptionsService [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestCopilotOptionsService() { } - public Task IsRefineOptionEnabledAsync() - => Task.FromResult(true); + public async Task IsRefineOptionEnabledAsync() + => true; - public Task IsCodeAnalysisOptionEnabledAsync() - => Task.FromResult(true); + public async Task IsCodeAnalysisOptionEnabledAsync() + => true; - public Task IsOnTheFlyDocsOptionEnabledAsync() - => Task.FromResult(true); + public async Task IsOnTheFlyDocsOptionEnabledAsync() + => true; - public Task IsGenerateDocumentationCommentOptionEnabledAsync() - => Task.FromResult(true); + public async Task IsGenerateDocumentationCommentOptionEnabledAsync() + => true; - public Task IsImplementNotImplementedExceptionEnabledAsync() - => Task.FromResult(true); + public async Task IsImplementNotImplementedExceptionEnabledAsync() + => true; } [ExportLanguageService(typeof(ICopilotCodeAnalysisService), LanguageNames.CSharp), Shared, PartNotDiscoverable] @@ -649,8 +649,8 @@ public Task> GetCachedDocumentDiagnosticsAsync(Docume public Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken) => throw new NotImplementedException(); - public Task IsAvailableAsync(CancellationToken cancellationToken) - => Task.FromResult(true); + public async Task IsAvailableAsync(CancellationToken cancellationToken) + => true; public Task IsFileExcludedAsync(string filePath, CancellationToken cancellationToken) => throw new NotImplementedException(); @@ -661,22 +661,22 @@ public Task StartRefinementSessionAsync(Document oldDocument, Document newDocume Task<(Dictionary? responseDictionary, bool isQuotaExceeded)> ICopilotCodeAnalysisService.GetDocumentationCommentAsync(DocumentationCommentProposal proposal, CancellationToken cancellationToken) => throw new NotImplementedException(); - public Task> ImplementNotImplementedExceptionsAsync( + public async Task> ImplementNotImplementedExceptionsAsync( Document document, ImmutableDictionary> methodOrProperties, CancellationToken cancellationToken) { if (SetupFixAll != null) { - return Task.FromResult(SetupFixAll.Invoke(document, methodOrProperties, cancellationToken)); + return SetupFixAll.Invoke(document, methodOrProperties, cancellationToken); } if (PrepareUsingSingleFakeResult != null) { - return Task.FromResult(CreateSingleNodeResult(methodOrProperties, PrepareUsingSingleFakeResult)); + return CreateSingleNodeResult(methodOrProperties, PrepareUsingSingleFakeResult); } - return Task.FromResult(ImmutableDictionary.Empty); + return ImmutableDictionary.Empty; } private static ImmutableDictionary CreateSingleNodeResult( @@ -692,9 +692,9 @@ private static ImmutableDictionary CreateSing return resultsBuilder.ToImmutable(); } - public Task IsImplementNotImplementedExceptionsAvailableAsync(CancellationToken cancellationToken) + public async Task IsImplementNotImplementedExceptionsAvailableAsync(CancellationToken cancellationToken) { - return Task.FromResult(true); + return true; } public Task GetOnTheFlyDocsPromptAsync(OnTheFlyDocsInfo onTheFlyDocsInfo, CancellationToken cancellationToken) diff --git a/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs b/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs index 7ca3b8ac3e7c9..97d7a938fcb34 100644 --- a/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs +++ b/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs @@ -46,11 +46,11 @@ protected override IEnumerable GetCodeRefactoringProvid return [new CSharpExtractClassCodeRefactoringProvider(service)]; } - protected override Task CreateWorkspaceImplAsync() + protected override async Task CreateWorkspaceImplAsync() { var unusedCompilationOptions = new CSharpCompilationOptions(OutputKind.NetModule); var unusedParseOptions = new CSharpParseOptions(LanguageVersion.CSharp1); - return Task.FromResult(TestWorkspace.Create(WorkspaceKind, LanguageNames.CSharp, unusedCompilationOptions, unusedParseOptions)); + return TestWorkspace.Create(WorkspaceKind, LanguageNames.CSharp, unusedCompilationOptions, unusedParseOptions); } } diff --git a/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs index 1403c022fbd82..2676ce6666df3 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs @@ -78,14 +78,14 @@ public override void Apply(Workspace workspace, CancellationToken cancellationTo operation.Apply(workspace, cancellationToken); } - internal override Task TryApplyAsync( + internal override async Task TryApplyAsync( Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) { var operation = GetApplyChangesOperation(workspace); if (operation is null) - return SpecializedTasks.False; + return false; - return operation.TryApplyAsync(workspace, originalSolution, progressTracker, cancellationToken); + return await operation.TryApplyAsync(workspace, originalSolution, progressTracker, cancellationToken).ConfigureAwait(false); } private ApplyChangesOperation? GetApplyChangesOperation(Workspace workspace) diff --git a/src/Features/Core/Portable/AddImport/CodeActions/InstallWithPackageManagerCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/InstallWithPackageManagerCodeAction.cs index 9d1f04f95a08d..04fa3b484b4c4 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/InstallWithPackageManagerCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/InstallWithPackageManagerCodeAction.cs @@ -22,11 +22,11 @@ private sealed class InstallWithPackageManagerCodeAction( public override string Title => FeaturesResources.Install_with_package_manager; - protected override Task> ComputeOperationsAsync( + protected override async Task> ComputeOperationsAsync( IProgress progress, CancellationToken cancellationToken) { - return Task.FromResult(ImmutableArray.Create( - new InstallWithPackageManagerCodeActionOperation(_installerService, _packageName))); + return ImmutableArray.Create( + new InstallWithPackageManagerCodeActionOperation(_installerService, _packageName)); } private sealed class InstallWithPackageManagerCodeActionOperation( diff --git a/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs index e2e3601ee0b2c..1e77a938c9a3a 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs @@ -24,14 +24,14 @@ public MetadataSymbolReferenceCodeAction(Document originalDocument, AddImportFix Contract.ThrowIfFalse(fixData.Kind == AddImportFixKind.MetadataSymbol); } - protected override Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) + protected override async Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) { var projectWithReference = project.Solution.GetRequiredProject(FixData.PortableExecutableReferenceProjectId); var reference = projectWithReference.MetadataReferences .OfType() .First(pe => pe.FilePath == FixData.PortableExecutableReferenceFilePathToAdd); - return Task.FromResult(new ApplyChangesOperation(project.AddMetadataReference(reference).Solution)); + return new ApplyChangesOperation(project.AddMetadataReference(reference).Solution); } } } diff --git a/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs index 30318b4a371b2..fff46496e5f09 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs @@ -37,19 +37,19 @@ public ProjectSymbolReferenceCodeAction( private static bool ShouldAddProjectReference(Document originalDocument, AddImportFixData fixData) => fixData.ProjectReferenceToAdd != null && fixData.ProjectReferenceToAdd != originalDocument.Project.Id; - protected override Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) + protected override async Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) { if (!ShouldAddProjectReference(this.OriginalDocument, this.FixData)) - return SpecializedTasks.Null(); + return null; var projectWithAddedReference = project.AddProjectReference(new ProjectReference(FixData.ProjectReferenceToAdd)); var applyOperation = new ApplyChangesOperation(projectWithAddedReference.Solution); if (isPreview) { - return Task.FromResult(applyOperation); + return applyOperation; } - return Task.FromResult(new AddProjectReferenceCodeActionOperation(OriginalDocument.Project.Id, FixData.ProjectReferenceToAdd, applyOperation)); + return new AddProjectReferenceCodeActionOperation(OriginalDocument.Project.Id, FixData.ProjectReferenceToAdd, applyOperation); } private sealed class AddProjectReferenceCodeActionOperation(ProjectId referencingProject, ProjectId referencedProject, ApplyChangesOperation applyOperation) : CodeActionOperation @@ -68,13 +68,13 @@ public override void Apply(Workspace workspace, CancellationToken cancellationTo _applyOperation.Apply(workspace, cancellationToken); } - internal override Task TryApplyAsync( + internal override async Task TryApplyAsync( Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) { if (!CanApply(workspace)) - return SpecializedTasks.False; + return false; - return _applyOperation.TryApplyAsync(workspace, originalSolution, progressTracker, cancellationToken); + return await _applyOperation.TryApplyAsync(workspace, originalSolution, progressTracker, cancellationToken).ConfigureAwait(false); } private bool CanApply(Workspace workspace) diff --git a/src/Features/Core/Portable/AddMissingReference/AddMissingReferenceCodeAction.cs b/src/Features/Core/Portable/AddMissingReference/AddMissingReferenceCodeAction.cs index d3662d9de4712..2f2bbaea89636 100644 --- a/src/Features/Core/Portable/AddMissingReference/AddMissingReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddMissingReference/AddMissingReferenceCodeAction.cs @@ -70,22 +70,22 @@ public static async Task CreateAsync(Project project, AssemblyIdenti return new AddMissingReferenceCodeAction(project, description, null, missingAssemblyIdentity); } - protected override Task> ComputeOperationsAsync( + protected override async Task> ComputeOperationsAsync( IProgress progress, CancellationToken cancellationToken) { // If we have a project reference to add, then add it if (_projectReferenceToAdd != null) { // note: no need to post process since we are just adding a project reference and not making any code changes. - return Task.FromResult(ImmutableArray.Create( - new ApplyChangesOperation(_project.AddProjectReference(_projectReferenceToAdd).Solution))); + return ImmutableArray.Create( + new ApplyChangesOperation(_project.AddProjectReference(_projectReferenceToAdd).Solution)); } else { // We didn't have any project, so we need to try adding a metadata reference var factoryService = _project.Solution.Services.GetRequiredService(); var operation = factoryService.CreateAddMetadataReferenceOperation(_project.Id, _missingAssemblyIdentity); - return Task.FromResult(ImmutableArray.Create(operation)); + return ImmutableArray.Create(operation); } } } diff --git a/src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.cs b/src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.cs index 3489f4c596dc1..036aa84ba4bb1 100644 --- a/src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.cs +++ b/src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.cs @@ -30,6 +30,6 @@ internal sealed class InstallPackageDirectlyCodeAction( ? string.Format(FeaturesResources.Use_local_version_0, versionOpt) : string.Format(FeaturesResources.Install_version_0, versionOpt); - protected override Task> ComputeOperationsAsync(IProgress progress, CancellationToken cancellationToken) - => Task.FromResult(ImmutableArray.Create(_installPackageOperation)); + protected override async Task> ComputeOperationsAsync(IProgress progress, CancellationToken cancellationToken) + => ImmutableArray.Create(_installPackageOperation); } diff --git a/src/Features/Core/Portable/AddPackage/InstallWithPackageManagerCodeAction.cs b/src/Features/Core/Portable/AddPackage/InstallWithPackageManagerCodeAction.cs index 9bdda9c841eea..5309ff40e418b 100644 --- a/src/Features/Core/Portable/AddPackage/InstallWithPackageManagerCodeAction.cs +++ b/src/Features/Core/Portable/AddPackage/InstallWithPackageManagerCodeAction.cs @@ -19,11 +19,11 @@ internal sealed class InstallWithPackageManagerCodeAction( public override string Title => FeaturesResources.Install_with_package_manager; - protected override Task> ComputeOperationsAsync( + protected override async Task> ComputeOperationsAsync( IProgress progress, CancellationToken cancellationToken) { - return Task.FromResult(ImmutableArray.Create( - new InstallWithPackageManagerCodeActionOperation(this))); + return ImmutableArray.Create( + new InstallWithPackageManagerCodeActionOperation(this)); } private sealed class InstallWithPackageManagerCodeActionOperation( diff --git a/src/Features/Core/Portable/BraceCompletion/AbstractBraceCompletionService.cs b/src/Features/Core/Portable/BraceCompletion/AbstractBraceCompletionService.cs index b467249f4a070..32dd9baa90412 100644 --- a/src/Features/Core/Portable/BraceCompletion/AbstractBraceCompletionService.cs +++ b/src/Features/Core/Portable/BraceCompletion/AbstractBraceCompletionService.cs @@ -38,19 +38,19 @@ internal abstract class AbstractBraceCompletionService : IBraceCompletionService public abstract bool AllowOverType(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken); - public ValueTask HasBraceCompletionAsync(BraceCompletionContext context, Document document, CancellationToken cancellationToken) + public async ValueTask HasBraceCompletionAsync(BraceCompletionContext context, Document document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!context.HasCompletionForOpeningBrace(OpeningBrace)) - return ValueTask.FromResult(false); + return false; var openingToken = context.GetOpeningToken(); if (!NeedsSemantics) - return ValueTask.FromResult(IsValidOpenBraceTokenAtPosition(context.Document.Text, openingToken, context.OpeningPoint)); + return IsValidOpenBraceTokenAtPosition(context.Document.Text, openingToken, context.OpeningPoint); // Pass along a document with frozen partial semantics. Brace completion is a highly latency sensitive // operation. We don't want to wait on things like source generators to figure things out. - return IsValidOpenBraceTokenAtPositionAsync(document.WithFrozenPartialSemantics(cancellationToken), openingToken, context.OpeningPoint, cancellationToken); + return await IsValidOpenBraceTokenAtPositionAsync(document.WithFrozenPartialSemantics(cancellationToken), openingToken, context.OpeningPoint, cancellationToken).ConfigureAwait(false); } public BraceCompletionResult GetBraceCompletion(BraceCompletionContext context) diff --git a/src/Features/Core/Portable/ChangeSignature/DelegateInvokeMethodReferenceFinder.cs b/src/Features/Core/Portable/ChangeSignature/DelegateInvokeMethodReferenceFinder.cs index 832571f7667e0..7c89b81cbd770 100644 --- a/src/Features/Core/Portable/ChangeSignature/DelegateInvokeMethodReferenceFinder.cs +++ b/src/Features/Core/Portable/ChangeSignature/DelegateInvokeMethodReferenceFinder.cs @@ -64,7 +64,7 @@ protected override async ValueTask> DetermineCascadedSym return result.ToImmutableAndClear(); } - protected override Task DetermineDocumentsToSearchAsync( + protected override async Task DetermineDocumentsToSearchAsync( IMethodSymbol symbol, HashSet? globalAliases, Project project, @@ -76,8 +76,6 @@ protected override Task DetermineDocumentsToSearchAsync( { foreach (var document in project.Documents) processResult(document, processResultData); - - return Task.CompletedTask; } protected override void FindReferencesInDocument( diff --git a/src/Features/Core/Portable/CodeFixes/CodeFixCollection.cs b/src/Features/Core/Portable/CodeFixes/CodeFixCollection.cs index a5d813b79a1f4..249f4e6c6a875 100644 --- a/src/Features/Core/Portable/CodeFixes/CodeFixCollection.cs +++ b/src/Features/Core/Portable/CodeFixes/CodeFixCollection.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; diff --git a/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureCodeStyle/ConfigureCodeStyleOptionCodeFixProvider.cs b/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureCodeStyle/ConfigureCodeStyleOptionCodeFixProvider.cs index 836235535dff4..f8a3c696bdf63 100644 --- a/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureCodeStyle/ConfigureCodeStyleOptionCodeFixProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureCodeStyle/ConfigureCodeStyleOptionCodeFixProvider.cs @@ -52,11 +52,11 @@ public bool IsFixableDiagnostic(Diagnostic diagnostic) public FixAllProvider? GetFixAllProvider() => null; - public Task> GetFixesAsync(TextDocument document, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) - => Task.FromResult(GetConfigurations(document.Project, diagnostics)); + public async Task> GetFixesAsync(TextDocument document, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) + => GetConfigurations(document.Project, diagnostics); - public Task> GetFixesAsync(Project project, IEnumerable diagnostics, CancellationToken cancellationToken) - => Task.FromResult(GetConfigurations(project, diagnostics)); + public async Task> GetFixesAsync(Project project, IEnumerable diagnostics, CancellationToken cancellationToken) + => GetConfigurations(project, diagnostics); private static ImmutableArray GetConfigurations(Project project, IEnumerable diagnostics) { diff --git a/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.cs b/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.cs index 3a3d88501982b..74c7d6c3074c4 100644 --- a/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.cs @@ -44,11 +44,11 @@ public bool IsFixableDiagnostic(Diagnostic diagnostic) public FixAllProvider? GetFixAllProvider() => null; - public Task> GetFixesAsync(TextDocument document, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) - => Task.FromResult(GetConfigurations(document.Project, diagnostics, cancellationToken)); + public async Task> GetFixesAsync(TextDocument document, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) + => GetConfigurations(document.Project, diagnostics, cancellationToken); - public Task> GetFixesAsync(Project project, IEnumerable diagnostics, CancellationToken cancellationToken) - => Task.FromResult(GetConfigurations(project, diagnostics, cancellationToken)); + public async Task> GetFixesAsync(Project project, IEnumerable diagnostics, CancellationToken cancellationToken) + => GetConfigurations(project, diagnostics, cancellationToken); private static ImmutableArray GetConfigurations(Project project, IEnumerable diagnostics, CancellationToken cancellationToken) { diff --git a/src/Features/Core/Portable/CodeFixes/Service/CodeFixService.FixAllPredefinedDiagnosticProvider.cs b/src/Features/Core/Portable/CodeFixes/Service/CodeFixService.FixAllPredefinedDiagnosticProvider.cs index 90190f331627c..bc6c93c86add6 100644 --- a/src/Features/Core/Portable/CodeFixes/Service/CodeFixService.FixAllPredefinedDiagnosticProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/Service/CodeFixService.FixAllPredefinedDiagnosticProvider.cs @@ -19,13 +19,13 @@ private sealed class FixAllPredefinedDiagnosticProvider : FixAllContext.Diagnost public FixAllPredefinedDiagnosticProvider(ImmutableArray diagnostics) => _diagnostics = diagnostics; - public override Task> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) - => Task.FromResult>(_diagnostics); + public override async Task> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) + => _diagnostics; - public override Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) - => Task.FromResult>(_diagnostics); + public override async Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) + => _diagnostics; - public override Task> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) - => SpecializedTasks.EmptyEnumerable(); + public override async Task> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) + => []; } } diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionBatchFixAllProvider.cs b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionBatchFixAllProvider.cs index 1aa81ab578563..d8d0e75811b5c 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionBatchFixAllProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionBatchFixAllProvider.cs @@ -196,12 +196,11 @@ private static Action> GetRegisterCodeFix }; } - protected virtual Task AddProjectFixesAsync( + protected virtual async Task AddProjectFixesAsync( Project project, ImmutableArray diagnostics, ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> fixes, FixAllState fixAllState, CancellationToken cancellationToken) { - return Task.CompletedTask; } public virtual async Task TryGetMergedFixAsync( @@ -216,7 +215,7 @@ protected virtual Task AddProjectFixesAsync( if (newSolution != null && newSolution != solution) { var title = FixAllHelper.GetDefaultFixAllTitle(fixAllState.Scope, title: fixAllState.DiagnosticIds.First(), fixAllState.Document!, fixAllState.Project); - return CodeAction.SolutionChangeAction.Create(title, _ => Task.FromResult(newSolution), title); + return CodeAction.SolutionChangeAction.Create(title, async _ => newSolution, title); } return null; diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs index d32c1f1e9e1df..d2b64e7d0c591 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs @@ -57,10 +57,10 @@ private sealed class GlobalSuppressionSolutionChangeAction( Func, CancellationToken, Task> createChangedSolution, string equivalenceKey) : SolutionChangeAction(title, createChangedSolution, equivalenceKey, CodeActionPriority.Default, CodeActionCleanup.Default) { - protected override Task PostProcessChangesAsync(Document document, CancellationToken cancellationToken) + protected override async Task PostProcessChangesAsync(Document document, CancellationToken cancellationToken) { // PERF: We don't to formatting on the entire global suppressions document, but instead do it for each attribute individual in the fixer. - return Task.FromResult(document); + return document; } } diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction.BatchFixer.cs b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction.BatchFixer.cs index ec1584616a016..6ea562e6e40ec 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction.BatchFixer.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction.BatchFixer.cs @@ -146,7 +146,7 @@ public override async Task TryGetMergedFixAsync( var batchAttributeRemoveFix = CodeAction.Create( attributeRemoveFixes.First().Title, - createChangedSolution: ct => Task.FromResult(currentSolution), + createChangedSolution: async ct => currentSolution, equivalenceKey: fixAllState.CodeActionEquivalenceKey); newBatchOfFixes.Insert(0, (diagnostic: null, batchAttributeRemoveFix)); diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.cs b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.cs index e5e5b8521de94..a726c631255ea 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.cs @@ -138,13 +138,13 @@ private SyntaxToken GetAdjustedTokenForPragmaRestore(SyntaxToken token, SyntaxNo return token; } - public Task> GetFixesAsync( + public async Task> GetFixesAsync( TextDocument textDocument, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) { if (textDocument is not Document document) - return Task.FromResult(ImmutableArray.Empty); + return ImmutableArray.Empty; - return GetSuppressionsAsync(document, span, diagnostics, skipSuppressMessage: false, skipUnsuppress: false, cancellationToken: cancellationToken); + return await GetSuppressionsAsync(document, span, diagnostics, skipSuppressMessage: false, skipUnsuppress: false, cancellationToken: cancellationToken).ConfigureAwait(false); } internal async Task> GetPragmaSuppressionsAsync(Document document, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) diff --git a/src/Features/Core/Portable/CodeLens/CodeLensReferencesService.cs b/src/Features/Core/Portable/CodeLens/CodeLensReferencesService.cs index 1eea7eaac7c52..1d33c509c2e16 100644 --- a/src/Features/Core/Portable/CodeLens/CodeLensReferencesService.cs +++ b/src/Features/Core/Portable/CodeLens/CodeLensReferencesService.cs @@ -91,11 +91,11 @@ public async ValueTask GetProjectCodeLensVersionAsync(Solution sol { var projectVersion = await GetProjectCodeLensVersionAsync(solution, documentId.ProjectId, cancellationToken).ConfigureAwait(false); return await FindAsync(solution, documentId, syntaxNode, - progress => Task.FromResult(new ReferenceCount( + async progress => new ReferenceCount( progress.SearchCap > 0 ? Math.Min(progress.ReferencesCount, progress.SearchCap) - : progress.ReferencesCount, progress.SearchCapReached, projectVersion.ToString())), - progress => Task.FromResult(new ReferenceCount(progress.SearchCap, IsCapped: true, projectVersion.ToString())), + : progress.ReferencesCount, progress.SearchCapReached, projectVersion.ToString()), + async progress => new ReferenceCount(progress.SearchCap, IsCapped: true, projectVersion.ToString()), maxSearchResults, cancellationToken).ConfigureAwait(false); } diff --git a/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.RenameFileEditor.cs b/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.RenameFileEditor.cs index 73607e6b9e236..7b0de443d6fe9 100644 --- a/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.RenameFileEditor.cs +++ b/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.RenameFileEditor.cs @@ -28,8 +28,7 @@ public override async Task> GetOperationsAsy return [new ApplyChangesOperation(newSolution)]; } - public override Task GetModifiedSolutionAsync() - => Task.FromResult( - SemanticDocument.Project.Solution.WithDocumentName(SemanticDocument.Document.Id, FileName)); + public override async Task GetModifiedSolutionAsync() + => SemanticDocument.Project.Solution.WithDocumentName(SemanticDocument.Document.Id, FileName); } } diff --git a/src/Features/Core/Portable/Completion/CommonCompletionProvider.cs b/src/Features/Core/Portable/Completion/CommonCompletionProvider.cs index be2eabb3e952e..0cd16958e722c 100644 --- a/src/Features/Core/Portable/Completion/CommonCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/CommonCompletionProvider.cs @@ -117,8 +117,8 @@ public override async Task GetChangeAsync(Document document, C public virtual Task GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) => GetTextChangeAsync(selectedItem, ch, cancellationToken); - protected virtual Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) - => SpecializedTasks.Default(); + protected virtual async Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + => null; protected static CompletionItem CreateSuggestionModeItem(string? displayText, string? description) { diff --git a/src/Features/Core/Portable/Completion/CompletionProvider.cs b/src/Features/Core/Portable/Completion/CompletionProvider.cs index c16459cb06398..975380a6b9c94 100644 --- a/src/Features/Core/Portable/Completion/CompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/CompletionProvider.cs @@ -60,8 +60,8 @@ internal virtual async Task IsSyntacticTriggerCharacterAsync(Document docu /// /// Gets the description of the specified item. /// - public virtual Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) - => Task.FromResult(CompletionDescription.Empty); + public virtual async Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) + => CompletionDescription.Empty; internal virtual Task GetDescriptionAsync(Document document, CompletionItem item, CompletionOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken) #pragma warning disable RS0030 // Do not used banned APIs @@ -74,8 +74,8 @@ internal virtual async Task IsSyntacticTriggerCharacterAsync(Document docu /// The current document. /// The item to be committed. /// The optional key character that caused the commit. - public virtual Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) - => Task.FromResult(CompletionChange.Create(new TextChange(item.Span, item.DisplayText))); + public virtual async Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) + => CompletionChange.Create(new TextChange(item.Span, item.DisplayText)); /// /// True if the provider produces snippet items. diff --git a/src/Features/Core/Portable/Completion/CompletionService.ProviderManager.cs b/src/Features/Core/Portable/Completion/CompletionService.ProviderManager.cs index 72ec826ec8b1c..d49fd9bbf6a7e 100644 --- a/src/Features/Core/Portable/Completion/CompletionService.ProviderManager.cs +++ b/src/Features/Core/Portable/Completion/CompletionService.ProviderManager.cs @@ -81,7 +81,7 @@ private IReadOnlyList> GetL return _lazyImportedProviders; } - private ValueTask ProcessBatchAsync(ImmutableSegmentedList> referencesList, CancellationToken cancellationToken) + private async ValueTask ProcessBatchAsync(ImmutableSegmentedList> referencesList, CancellationToken cancellationToken) { foreach (var references in referencesList) { @@ -90,8 +90,6 @@ private ValueTask ProcessBatchAsync(ImmutableSegmentedList GetCachedProjectCompletionProvidersOrQueueLoadInBackground(Project? project, CompletionOptions options) diff --git a/src/Features/Core/Portable/Completion/CompletionService.cs b/src/Features/Core/Portable/Completion/CompletionService.cs index c880d896d33f9..6d2195ce377ba 100644 --- a/src/Features/Core/Portable/Completion/CompletionService.cs +++ b/src/Features/Core/Portable/Completion/CompletionService.cs @@ -375,9 +375,9 @@ internal static bool IsAllPunctuation(string filterText) return true; } - internal virtual Task IsSpeculativeTypeParameterContextAsync(Document document, int position, CancellationToken cancellationToken) + internal virtual async ValueTask IsSpeculativeTypeParameterContextAsync(Document document, int position, CancellationToken cancellationToken) { - return SpecializedTasks.False; + return false; } /// diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractKeywordCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractKeywordCompletionProvider.cs index 2c44eb5daa37e..39136c307568d 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractKeywordCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractKeywordCompletionProvider.cs @@ -72,6 +72,6 @@ private async Task> RecommendKeywordsAsync( return result.ToImmutableAndClear(); } - public sealed override Task GetTextChangeAsync(Document document, CompletionItem item, char? ch, CancellationToken cancellationToken) - => Task.FromResult((TextChange?)new TextChange(item.Span, item.DisplayText)); + public sealed override async Task GetTextChangeAsync(Document document, CompletionItem item, char? ch, CancellationToken cancellationToken) + => (TextChange?)new TextChange(item.Span, item.DisplayText); } diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractObjectCreationCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractObjectCreationCompletionProvider.cs index 94e1170f2e2f9..9f754edc28a87 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractObjectCreationCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractObjectCreationCompletionProvider.cs @@ -44,12 +44,12 @@ protected override CompletionItem CreateItem( supportedPlatforms: supportedPlatformData); } - protected override Task> GetSymbolsAsync( + protected override async Task> GetSymbolsAsync( CompletionContext? completionContext, TSyntaxContext context, int position, CompletionOptions options, CancellationToken cancellationToken) { var newExpression = GetObjectCreationNewExpression(context.SyntaxTree, position, cancellationToken); if (newExpression == null) - return SpecializedTasks.EmptyImmutableArray(); + return []; var typeInferenceService = context.GetRequiredLanguageService(); var type = typeInferenceService.InferType( @@ -62,20 +62,20 @@ protected override Task> GetSymbolsAsync( type = arrayType.ElementType; if (type == null) - return SpecializedTasks.EmptyImmutableArray(); + return []; // Unwrap nullable if (type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) type = type.GetTypeArguments().Single(); if (type.SpecialType == SpecialType.System_Void) - return SpecializedTasks.EmptyImmutableArray(); + return []; if (type.ContainsAnonymousType()) - return SpecializedTasks.EmptyImmutableArray(); + return []; if (!type.CanBeReferencedByName) - return SpecializedTasks.EmptyImmutableArray(); + return []; // Normally the user can't say things like "new IList". Except for "IList[] x = new |". // In this case we do want to allow them to preselect certain types in the completion @@ -85,18 +85,18 @@ protected override Task> GetSymbolsAsync( if (type.TypeKind is TypeKind.Interface or TypeKind.Pointer or TypeKind.Dynamic || type.IsAbstract) { - return SpecializedTasks.EmptyImmutableArray(); + return []; } if (type is ITypeParameterSymbol typeParameter && !typeParameter.HasConstructorConstraint) - return SpecializedTasks.EmptyImmutableArray(); + return []; } if (!type.IsEditorBrowsable(options.MemberDisplayOptions.HideAdvancedMembers, context.SemanticModel.Compilation)) - return SpecializedTasks.EmptyImmutableArray(); + return []; // In the case of array creation, we don't offer a preselected/hard-selected item because // the user may want an implicitly-typed array creation - return Task.FromResult(ImmutableArray.Create(new SymbolAndSelectionInfo(Symbol: type, Preselect: !isArray))); + return ImmutableArray.Create(new SymbolAndSelectionInfo(Symbol: type, Preselect: !isArray)); } } diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractPartialTypeCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractPartialTypeCompletionProvider.cs index 01fac320c09b8..54fdc40b7a468 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractPartialTypeCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractPartialTypeCompletionProvider.cs @@ -110,9 +110,9 @@ private static bool NotNewDeclaredMember(INamedTypeSymbol symbol, TSyntaxContext internal override Task GetDescriptionWorkerAsync(Document document, CompletionItem item, CompletionOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, displayOptions, cancellationToken); - public override Task GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + public override async Task GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { var insertionText = SymbolCompletionItem.GetInsertionText(selectedItem); - return Task.FromResult(new TextChange(selectedItem.Span, insertionText)); + return new TextChange(selectedItem.Span, insertionText); } } diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs index 1a11cdd1da824..9fe46ca17d807 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs @@ -379,8 +379,8 @@ private async Task> GetItemsAsync( protected virtual bool IsExclusive() => false; - protected virtual Task IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken) - => SpecializedTasks.True; + protected virtual async Task IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken) + => true; private static Dictionary UnionSymbols( ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray symbols)> linkedContextSymbolLists) @@ -466,8 +466,8 @@ private static Dictionary> FindSymbolsMissingIn return missingSymbols; } - public sealed override Task GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) - => Task.FromResult(new TextChange(selectedItem.Span, GetInsertionText(selectedItem, ch))); + public sealed override async Task GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + => new TextChange(selectedItem.Span, GetInsertionText(selectedItem, ch)); private string GetInsertionText(CompletionItem item, char? ch) { diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs index d42f558318a47..0168eb4651f89 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs @@ -25,10 +25,9 @@ internal abstract class AbstractImportCompletionProvider : LSPCompletionProvider protected abstract Task ShouldProvideParenthesisCompletionAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken); protected abstract void LogCommit(); - public Task NotifyCommittingItemAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) + public async Task NotifyCommittingItemAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) { LogCommit(); - return Task.CompletedTask; } internal override bool IsExpandItemProvider => true; diff --git a/src/Features/Core/Portable/ConvertLinq/AbstractConvertLinqQueryToForEachProvider.cs b/src/Features/Core/Portable/ConvertLinq/AbstractConvertLinqQueryToForEachProvider.cs index 385012c4d2d87..deaa61c5bce4f 100644 --- a/src/Features/Core/Portable/ConvertLinq/AbstractConvertLinqQueryToForEachProvider.cs +++ b/src/Features/Core/Portable/ConvertLinq/AbstractConvertLinqQueryToForEachProvider.cs @@ -46,7 +46,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte context.RegisterRefactoring( CodeAction.Create( Title, - c => Task.FromResult(document.WithSyntaxRoot(documentUpdateInfo.UpdateRoot(root))), + async c => document.WithSyntaxRoot(documentUpdateInfo.UpdateRoot(root)), Title), queryExpression.Span); } diff --git a/src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConvertForEachToLinqQueryProvider.cs b/src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConvertForEachToLinqQueryProvider.cs index 994a2a9d97799..b7fbd35741236 100644 --- a/src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConvertForEachToLinqQueryProvider.cs +++ b/src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConvertForEachToLinqQueryProvider.cs @@ -142,7 +142,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte } } - private Task ApplyConversionAsync( + private async Task ApplyConversionAsync( IConverter converter, Document document, bool convertToQuery, @@ -152,7 +152,7 @@ private Task ApplyConversionAsync( converter.Convert(editor, convertToQuery, cancellationToken); var newRoot = editor.GetChangedRoot(); var rootWithLinqUsing = AddLinqUsing(converter, converter.ForEachInfo.SemanticModel, newRoot); - return Task.FromResult(document.WithSyntaxRoot(rootWithLinqUsing)); + return document.WithSyntaxRoot(rootWithLinqUsing); } /// diff --git a/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs b/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs index 4bcc920a74e59..c2e890257774f 100644 --- a/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs @@ -119,13 +119,13 @@ static string AddSeparators(string numericText, int interval) return result[0] == '_' ? result[1..] : result; } - static Task ReplaceTokenAsync(Document document, SyntaxNode root, SyntaxToken numericToken, long value, string text, string suffix) + static async Task ReplaceTokenAsync(Document document, SyntaxNode root, SyntaxToken numericToken, long value, string text, string suffix) { var generator = SyntaxGenerator.GetGenerator(document); var updatedToken = generator.NumericLiteralToken(text + suffix, (ulong)value) .WithTriviaFrom(numericToken); var updatedRoot = root.ReplaceToken(numericToken, updatedToken); - return Task.FromResult(document.WithSyntaxRoot(updatedRoot)); + return document.WithSyntaxRoot(updatedRoot); } (string prefix, string number, string suffix) GetNumericLiteralParts(string numericText) diff --git a/src/Features/Core/Portable/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringRefactoringProvider.cs b/src/Features/Core/Portable/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringRefactoringProvider.cs index db0e91296f327..1244fadf004d5 100644 --- a/src/Features/Core/Portable/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringRefactoringProvider.cs +++ b/src/Features/Core/Portable/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringRefactoringProvider.cs @@ -103,13 +103,13 @@ private static SyntaxNode CreateInterpolatedString(Document document, SyntaxNode generator.CreateInterpolatedStringEndToken()).WithTriviaFrom(literalExpression); } - private static Task UpdateDocumentAsync(Document document, SyntaxNode root, SyntaxToken token) + private static async Task UpdateDocumentAsync(Document document, SyntaxNode root, SyntaxToken token) { var syntaxFacts = document.GetRequiredLanguageService(); var literalExpression = token.GetRequiredParent(); - return Task.FromResult(document.WithSyntaxRoot( + return document.WithSyntaxRoot( root.ReplaceNode( literalExpression, - CreateInterpolatedString(document, literalExpression, syntaxFacts.IsVerbatimStringLiteral(token))))); + CreateInterpolatedString(document, literalExpression, syntaxFacts.IsVerbatimStringLiteral(token)))); } } diff --git a/src/Features/Core/Portable/Debugging/DebugInformationReaderProvider.cs b/src/Features/Core/Portable/Debugging/DebugInformationReaderProvider.cs index 57c6616b4b9e0..52b94e08b9c56 100644 --- a/src/Features/Core/Portable/Debugging/DebugInformationReaderProvider.cs +++ b/src/Features/Core/Portable/Debugging/DebugInformationReaderProvider.cs @@ -46,7 +46,7 @@ private sealed class Portable(MetadataReaderProvider pdbReaderProvider) : DebugI public override EditAndContinueMethodDebugInfoReader CreateEditAndContinueMethodDebugInfoReader() => EditAndContinueMethodDebugInfoReader.Create(_pdbReaderProvider.GetMetadataReader()); - public override ValueTask CopyContentToAsync(Stream stream, CancellationToken cancellationToken) + public override async ValueTask CopyContentToAsync(Stream stream, CancellationToken cancellationToken) { var reader = _pdbReaderProvider.GetMetadataReader(); unsafe @@ -54,8 +54,6 @@ public override ValueTask CopyContentToAsync(Stream stream, CancellationToken ca using var metadataStream = new UnmanagedMemoryStream(reader.MetadataPointer, reader.MetadataLength); metadataStream.CopyTo(stream); } - - return ValueTask.CompletedTask; } public override void Dispose() diff --git a/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs b/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs index 0c3ed361576ef..44ab3a135cd52 100644 --- a/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs +++ b/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs @@ -197,10 +197,10 @@ private async Task> FilterAndCreateSpansAsync documentsToSearch, cancellationToken).ConfigureAwait(false); } - protected virtual Task> GetAdditionalReferencesAsync( + protected virtual async ValueTask> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { - return SpecializedTasks.EmptyImmutableArray(); + return []; } private static async Task> CreateSpansAsync( diff --git a/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs b/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs index f87762dd30276..5ba173cc9947b 100644 --- a/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs +++ b/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs @@ -207,7 +207,7 @@ public ValueTask> GetDocumentDiagnosticsAsync(Documen cancellationToken); } - public ValueTask EmitSolutionUpdateAsync( + public async ValueTask EmitSolutionUpdateAsync( DebuggingSessionId sessionId, Solution solution, ImmutableDictionary runningProjects, @@ -217,10 +217,10 @@ public ValueTask EmitSolutionUpdateAsync( var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { - return ValueTask.FromResult(EmitSolutionUpdateResults.Empty); + return EmitSolutionUpdateResults.Empty; } - return debuggingSession.EmitSolutionUpdateAsync(solution, runningProjects, activeStatementSpanProvider, cancellationToken); + return await debuggingSession.EmitSolutionUpdateAsync(solution, runningProjects, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } public void CommitSolutionUpdate(DebuggingSessionId sessionId) @@ -239,7 +239,7 @@ public void DiscardSolutionUpdate(DebuggingSessionId sessionId) debuggingSession.DiscardSolutionUpdate(); } - public ValueTask>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) + public async ValueTask>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) @@ -247,18 +247,18 @@ public ValueTask>> GetBaseAct return default; } - return debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken); + return await debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken).ConfigureAwait(false); } - public ValueTask> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) + public async ValueTask> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { - return ValueTask.FromResult(ImmutableArray.Empty); + return ImmutableArray.Empty; } - return debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken); + return await debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } internal TestAccessor GetTestAccessor() diff --git a/src/Features/Core/Portable/EditAndContinue/IPdbMatchingSourceTextProvider.cs b/src/Features/Core/Portable/EditAndContinue/IPdbMatchingSourceTextProvider.cs index 35f21c48e4adf..d65ff0e616248 100644 --- a/src/Features/Core/Portable/EditAndContinue/IPdbMatchingSourceTextProvider.cs +++ b/src/Features/Core/Portable/EditAndContinue/IPdbMatchingSourceTextProvider.cs @@ -24,6 +24,6 @@ private NullPdbMatchingSourceTextProvider() { } - public ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) - => ValueTask.FromResult(null); + public async ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) + => null; } diff --git a/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedCompletionProvider.cs b/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedCompletionProvider.cs index 9f89c0e96515a..6e182ad2bd3ec 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedCompletionProvider.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedCompletionProvider.cs @@ -212,7 +212,7 @@ private static void ProvideCustomFormats(EmbeddedCompletionContext context) context.AddCustom("/", FeaturesResources.date_separator, FeaturesResources.date_separator_description); } - public override Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) + public override async Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) { // These values have always been added by us. var startString = item.GetProperty(StartKey); @@ -223,16 +223,16 @@ public override Task GetChangeAsync(Document document, Complet Contract.ThrowIfNull(lengthString); Contract.ThrowIfNull(newText); - return Task.FromResult(CompletionChange.Create( - new TextChange(new TextSpan(int.Parse(startString), int.Parse(lengthString)), newText))); + return CompletionChange.Create( + new TextChange(new TextSpan(int.Parse(startString), int.Parse(lengthString)), newText)); } - public override Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) + public override async Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { if (!item.TryGetProperty(DescriptionKey, out var description)) - return SpecializedTasks.Null(); + return null; - return Task.FromResult((CompletionDescription?)CompletionDescription.Create( - [new TaggedText(TextTags.Text, description)])); + return (CompletionDescription?)CompletionDescription.Create( + [new TaggedText(TextTags.Text, description)]); } } diff --git a/src/Features/Core/Portable/EmbeddedLanguages/Json/LanguageServices/AbstractJsonDetectionCodeFixProvider.cs b/src/Features/Core/Portable/EmbeddedLanguages/Json/LanguageServices/AbstractJsonDetectionCodeFixProvider.cs index a0416c4bb3e3e..b9ae7ce4dc6d9 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/Json/LanguageServices/AbstractJsonDetectionCodeFixProvider.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/Json/LanguageServices/AbstractJsonDetectionCodeFixProvider.cs @@ -32,10 +32,9 @@ protected AbstractJsonDetectionCodeFixProvider( public override ImmutableArray FixableDiagnosticIds => [AbstractJsonDetectionAnalyzer.DiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, FeaturesResources.Enable_all_JSON_editor_features, nameof(FeaturesResources.Enable_all_JSON_editor_features)); - return Task.CompletedTask; } public void Fix(SyntaxEditor editor, Diagnostic diagnostic, CancellationToken cancellationToken) @@ -50,13 +49,11 @@ public void Fix(SyntaxEditor editor, Diagnostic diagnostic, CancellationToken ca this.AddComment(editor, stringLiteral, commentContents); } - protected override Task FixAllAsync( + protected override async Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) Fix(editor, diagnostic, cancellationToken); - - return Task.CompletedTask; } } diff --git a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedCompletionProvider.cs b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedCompletionProvider.cs index 262367f29eecd..e5d37962ef1bc 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedCompletionProvider.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedCompletionProvider.cs @@ -442,7 +442,7 @@ bool IsInCharacterClassWorker(RegexNode parent, bool inCharacterClass) } } - public override Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) + public override async Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) { // These values have always been added by us. var startString = item.GetProperty(StartKey); @@ -452,19 +452,19 @@ public override Task GetChangeAsync(Document document, Complet // This value is optionally added in some cases and may not always be there. item.TryGetProperty(NewPositionKey, out var newPositionString); - return Task.FromResult(CompletionChange.Create( + return CompletionChange.Create( new TextChange(new TextSpan(int.Parse(startString), int.Parse(lengthString)), newText), - newPositionString == null ? null : int.Parse(newPositionString))); + newPositionString == null ? null : int.Parse(newPositionString)); } - public override Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) + public override async Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { if (!item.TryGetProperty(DescriptionKey, out var description)) { - return SpecializedTasks.Null(); + return null; } - return Task.FromResult(CompletionDescription.Create( - [new TaggedText(TextTags.Text, description)])); + return CompletionDescription.Create( + [new TaggedText(TextTags.Text, description)]); } } diff --git a/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs b/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs index bbbbdb6ce1450..916692a3d8c54 100644 --- a/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs +++ b/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs @@ -70,7 +70,7 @@ private void ClearCachedHandlers_WhileUnderLock() _cachedHandlers_useOnlyUnderLock.document.Clear(); } - private ValueTask RegisterExtensionInCurrentProcessAsync(string assemblyFilePath) + private async ValueTask RegisterExtensionInCurrentProcessAsync(string assemblyFilePath) { // Note: This method executes no extension code. And, as such, does not try to catch exceptions to // translate them accordingly to a failure that we send back to the client as part of the response. @@ -89,11 +89,11 @@ private ValueTask RegisterExtensionInCurrentProcessAsync(string assemblyFilePath assemblyFolderPath => new ExtensionFolder(this, assemblyFolderPath)); extensionFolder.RegisterAssembly(assemblyFilePath); - return default; + return; } } - private ValueTask UnregisterExtensionInCurrentProcessAsync(string assemblyFilePath) + private async ValueTask UnregisterExtensionInCurrentProcessAsync(string assemblyFilePath) { // Note: This method executes no extension code. And, as such, does not try to catch exceptions to // translate them accordingly to a failure that we send back to the client as part of the response. @@ -104,7 +104,7 @@ private ValueTask UnregisterExtensionInCurrentProcessAsync(string assemblyFilePa // to unload all ALCs needed to load it and the extensions within. Unloading will happen once the // runtime/gc determine the ALC is finally collectible. folderToUnload?.Unload(); - return default; + return; ExtensionFolder? Unregister() { @@ -144,7 +144,7 @@ private ValueTask UnregisterExtensionInCurrentProcessAsync(string assemblyFilePa } } - private ValueTask ResetInCurrentProcessAsync() + private async ValueTask ResetInCurrentProcessAsync() { // Note: This method executes no extension code. And, as such, does not try to catch exceptions to // translate them accordingly to a failure that we send back to the client as part of the response. @@ -161,8 +161,6 @@ private ValueTask ResetInCurrentProcessAsync() foreach (var (_, folderToUnload) in oldFolderPathToExtensionFolder) folderToUnload.Unload(); - - return default; } private async ValueTask GetExtensionMessageNamesInCurrentProcessAsync( diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/NewUnitTestingIncrementalAnalyzer.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/NewUnitTestingIncrementalAnalyzer.cs index 98ff20b113e32..50a7d6aceee73 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/NewUnitTestingIncrementalAnalyzer.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/NewUnitTestingIncrementalAnalyzer.cs @@ -36,10 +36,9 @@ public Task AnalyzeProjectAsync( cancellationToken); } - public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) + public async Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { _implementation.RemoveDocument(documentId); - return Task.CompletedTask; } } } diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs index 15c0db217f5c1..ec482cd1e5459 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs @@ -19,14 +19,14 @@ private sealed class DebuggerService(ImmutableArray capabilities) : IMan { private readonly ImmutableArray _capabilities = capabilities; - public ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) - => ValueTask.FromResult(ImmutableArray.Empty); + public async ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) + => ImmutableArray.Empty; - public ValueTask GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) - => ValueTask.FromResult(new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.Available)); + public async ValueTask GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) + => new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.Available); - public ValueTask> GetCapabilitiesAsync(CancellationToken cancellationToken) - => ValueTask.FromResult(_capabilities); + public async ValueTask> GetCapabilitiesAsync(CancellationToken cancellationToken) + => _capabilities; public ValueTask PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => ValueTask.CompletedTask; @@ -49,7 +49,7 @@ public readonly struct Update( } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = - (_, _, _) => ValueTask.FromResult(ImmutableArray.Empty); + async (_, _, _) => ImmutableArray.Empty; private readonly IEditAndContinueService _encService = services.GetRequiredService().Service; private DebuggingSessionId _sessionId; diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/LegacySolutionEvents/UnitTestingLegacySolutionEventsListener.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/LegacySolutionEvents/UnitTestingLegacySolutionEventsListener.cs index 27045155dbabf..c55f42fc2a8ba 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/LegacySolutionEvents/UnitTestingLegacySolutionEventsListener.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/LegacySolutionEvents/UnitTestingLegacySolutionEventsListener.cs @@ -45,10 +45,9 @@ public bool ShouldReportChanges(SolutionServices services) return service.HasRegisteredAnalyzerProviders; } - public ValueTask OnWorkspaceChangedAsync(WorkspaceChangeEventArgs args, CancellationToken cancellationToken) + public async ValueTask OnWorkspaceChangedAsync(WorkspaceChangeEventArgs args, CancellationToken cancellationToken) { var coordinator = GetCoordinator(args.NewSolution); coordinator?.OnWorkspaceChanged(args); - return ValueTask.CompletedTask; } } diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs index 7f767cb6c8737..e021b9b6f8bf4 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs @@ -45,15 +45,13 @@ protected AbstractGlobalOperationNotificationService( } } - private ValueTask ProcessEventsAsync(ImmutableSegmentedList list, CancellationToken cancellationToken) + private async ValueTask ProcessEventsAsync(ImmutableSegmentedList list, CancellationToken cancellationToken) { foreach (var value in list) { var eventHandler = value ? Started : Stopped; eventHandler?.Invoke(this, EventArgs.Empty); } - - return ValueTask.CompletedTask; } public IDisposable Start(string operation) diff --git a/src/Features/Core/Portable/FindUsages/DefaultExternalDefinitionItemProvider.cs b/src/Features/Core/Portable/FindUsages/DefaultExternalDefinitionItemProvider.cs index dfa94995ac4e3..ac0a89f5d327a 100644 --- a/src/Features/Core/Portable/FindUsages/DefaultExternalDefinitionItemProvider.cs +++ b/src/Features/Core/Portable/FindUsages/DefaultExternalDefinitionItemProvider.cs @@ -20,6 +20,6 @@ internal sealed class DefaultExternalDefinitionItemProvider() : IExternalDefinit /// Provides an extension point that allows for other workspace layers to add additional /// results to the results found by the FindReferences engine. /// - public Task GetThirdPartyDefinitionItemAsync(Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async ValueTask GetThirdPartyDefinitionItemAsync(Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken) + => null; } diff --git a/src/Features/Core/Portable/FindUsages/IExternalDefinitionItemProvider.cs b/src/Features/Core/Portable/FindUsages/IExternalDefinitionItemProvider.cs index bfab728b62a21..932f1c3ca41a1 100644 --- a/src/Features/Core/Portable/FindUsages/IExternalDefinitionItemProvider.cs +++ b/src/Features/Core/Portable/FindUsages/IExternalDefinitionItemProvider.cs @@ -10,6 +10,6 @@ namespace Microsoft.CodeAnalysis.FindUsages; internal interface IExternalDefinitionItemProvider : IWorkspaceService { - Task GetThirdPartyDefinitionItemAsync( + ValueTask GetThirdPartyDefinitionItemAsync( Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken); } diff --git a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs index 947ae6b37ea81..7eb8ba507080c 100644 --- a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs +++ b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs @@ -46,12 +46,12 @@ internal abstract partial class AbstractInitializeMemberFromParameterCodeRefacto protected abstract Accessibility DetermineDefaultPropertyAccessibility(); protected abstract SyntaxNode RemoveThrowNotImplemented(SyntaxNode propertySyntax); - protected sealed override Task> GetRefactoringsForAllParametersAsync( + protected sealed override async Task> GetRefactoringsForAllParametersAsync( Document document, SyntaxNode functionDeclaration, IMethodSymbol method, IBlockOperation? blockStatementOpt, ImmutableArray listOfParameterNodes, TextSpan parameterSpan, CancellationToken cancellationToken) { - return SpecializedTasks.EmptyImmutableArray(); + return []; } protected sealed override async Task> GetRefactoringsForSingleParameterAsync( diff --git a/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs b/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs index 04c51af3abbf4..5e077232d7b6c 100644 --- a/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs +++ b/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs @@ -18,13 +18,13 @@ internal abstract partial class AbstractSymbolDisplayService(LanguageServices se protected abstract AbstractSymbolDescriptionBuilder CreateDescriptionBuilder(SemanticModel semanticModel, int position, SymbolDescriptionOptions options, CancellationToken cancellationToken); - public Task> ToDescriptionPartsAsync(SemanticModel semanticModel, int position, ImmutableArray symbols, SymbolDescriptionOptions options, SymbolDescriptionGroups groups, CancellationToken cancellationToken) + public async Task> ToDescriptionPartsAsync(SemanticModel semanticModel, int position, ImmutableArray symbols, SymbolDescriptionOptions options, SymbolDescriptionGroups groups, CancellationToken cancellationToken) { if (symbols.Length == 0) - return SpecializedTasks.EmptyImmutableArray(); + return []; var builder = CreateDescriptionBuilder(semanticModel, position, options, cancellationToken); - return builder.BuildDescriptionAsync(symbols, groups); + return await builder.BuildDescriptionAsync(symbols, groups).ConfigureAwait(false); } public async Task>> ToDescriptionGroupsAsync( diff --git a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs index fdffff0191d32..31a28e8d7070a 100644 --- a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs +++ b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs @@ -167,18 +167,18 @@ private static int GetNamespaceInSpineCount(SyntaxNode node) private static bool ContainsMultipleTypesInSpine(SyntaxNode node) => node.AncestorsAndSelf().OfType().Count() > 1; - public Task MoveToNamespaceAsync( + public async Task MoveToNamespaceAsync( MoveToNamespaceAnalysisResult analysisResult, string targetNamespace, CancellationToken cancellationToken) { if (!analysisResult.CanPerform) - return Task.FromResult(MoveToNamespaceResult.Failed); + return MoveToNamespaceResult.Failed; return analysisResult.Container switch { - MoveToNamespaceAnalysisResult.ContainerType.Namespace => MoveItemsInNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, cancellationToken), - MoveToNamespaceAnalysisResult.ContainerType.NamedType => MoveTypeToNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, cancellationToken), + MoveToNamespaceAnalysisResult.ContainerType.Namespace => await MoveItemsInNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, cancellationToken).ConfigureAwait(false), + MoveToNamespaceAnalysisResult.ContainerType.NamedType => await MoveTypeToNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, cancellationToken).ConfigureAwait(false), _ => throw new InvalidOperationException(), }; } diff --git a/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.CachedDocumentSearch.cs b/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.CachedDocumentSearch.cs index d5b37c9fa304b..ec8df45129b0d 100644 --- a/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.CachedDocumentSearch.cs +++ b/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.CachedDocumentSearch.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.Remote; -using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Threading; using Roslyn.Utilities; @@ -157,18 +156,18 @@ await Parallel.ForEachAsync( } } - private static Task GetIndexAsync( + private static async ValueTask GetIndexAsync( IChecksummedPersistentStorageService storageService, DocumentKey documentKey, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) - return SpecializedTasks.Null(); + return null; // Retrieve the string table we use to dedupe strings. If we can't get it, that means the solution has // fully loaded and we've switched over to normal navto lookup. if (!ShouldSearchCachedDocuments(out var cachedIndexMap, out var stringTable)) - return SpecializedTasks.Null(); + return null; // Add the async lazy to compute the index for this document. Or, return the existing cached one if already // present. This ensures that subsequent searches that are run while the solution is still loading are fast @@ -181,6 +180,6 @@ await Parallel.ForEachAsync( static t => AsyncLazy.Create(static (t, c) => TopLevelSyntaxTreeIndex.LoadAsync(t.service, t.documentKey, checksum: null, t.stringTable, c), arg: t)); - return asyncLazy.GetValueAsync(cancellationToken); + return await asyncLazy.GetValueAsync(cancellationToken).ConfigureAwait(false); } } diff --git a/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs b/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs index 4db3bc8000888..d27eedd9e5ced 100644 --- a/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs +++ b/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; -using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; @@ -196,22 +195,22 @@ await service.SearchDocumentAsync( cancellationToken).ConfigureAwait(false); } - private Task SearchCurrentProjectAsync( + private async Task SearchCurrentProjectAsync( NavigateToDocumentSupport documentSupport, CancellationToken cancellationToken) { if (_activeDocument == null) - return Task.CompletedTask; + return; var activeProject = _activeDocument.Project; - return SearchSpecificProjectsAsync( + await SearchSpecificProjectsAsync( // Because we're only searching the current project, it's fine to bring that project fully up to date before // searching it. We only do the work to search cached files when doing the initial load of something huge // (the full solution). isFullyLoaded: true, documentSupport, [[activeProject]], - cancellationToken); + cancellationToken).ConfigureAwait(false); } private INavigateToSearchService GetNavigateToSearchService(Project project) diff --git a/src/Features/Core/Portable/Navigation/DefaultSymbolNavigationService.cs b/src/Features/Core/Portable/Navigation/DefaultSymbolNavigationService.cs index d119541fd91d4..b6fb06cecd542 100644 --- a/src/Features/Core/Portable/Navigation/DefaultSymbolNavigationService.cs +++ b/src/Features/Core/Portable/Navigation/DefaultSymbolNavigationService.cs @@ -12,12 +12,12 @@ namespace Microsoft.CodeAnalysis.Navigation; internal sealed class DefaultSymbolNavigationService : ISymbolNavigationService { - public Task GetNavigableLocationAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task GetNavigableLocationAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) + => null; - public Task TrySymbolNavigationNotifyAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task TrySymbolNavigationNotifyAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) + => false; - public Task<(string filePath, LinePosition linePosition)?> GetExternalNavigationSymbolLocationAsync(DefinitionItem definitionItem, CancellationToken cancellationToken) - => Task.FromResult<(string filePath, LinePosition linePosition)?>(null); + public async Task<(string filePath, LinePosition linePosition)?> GetExternalNavigationSymbolLocationAsync(DefinitionItem definitionItem, CancellationToken cancellationToken) + => null; } diff --git a/src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs b/src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs index 006506a55e49c..503e1fc3153a9 100644 --- a/src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs +++ b/src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs @@ -30,14 +30,14 @@ internal interface IDocumentNavigationService : IWorkspaceService internal abstract class AbstractDocumentNavigationService : IDocumentNavigationService { - public virtual Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) - => SpecializedTasks.False; + public virtual async Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) + => false; public virtual Task CanNavigateToPositionAsync(Workspace workspace, DocumentId documentId, int position, int virtualSpace, bool allowInvalidPosition, CancellationToken cancellationToken) => CanNavigateToSpanAsync(workspace, documentId, new TextSpan(position, 0), allowInvalidSpan: allowInvalidPosition, cancellationToken); - public virtual Task GetLocationForSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public virtual async Task GetLocationForSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) + => null; public virtual Task GetLocationForPositionAsync(Workspace workspace, DocumentId documentId, int position, int virtualSpace, bool allowInvalidPosition, CancellationToken cancellationToken) => GetLocationForSpanAsync(workspace, documentId, new TextSpan(position, 0), allowInvalidSpan: allowInvalidPosition, cancellationToken); diff --git a/src/Features/Core/Portable/Navigation/INavigableLocation.cs b/src/Features/Core/Portable/Navigation/INavigableLocation.cs index 84eee62f5d52c..d71f6b623a551 100644 --- a/src/Features/Core/Portable/Navigation/INavigableLocation.cs +++ b/src/Features/Core/Portable/Navigation/INavigableLocation.cs @@ -33,11 +33,10 @@ public Task NavigateToAsync(NavigationOptions options, CancellationToken c public static class TestAccessor { #pragma warning disable VSTHRD200 // Use "Async" suffix for async methods - public static Task Create(bool value) + public static async Task Create(bool value) #pragma warning restore VSTHRD200 // Use "Async" suffix for async methods { - return Task.FromResult( - new NavigableLocation((_, _) => value ? SpecializedTasks.True : SpecializedTasks.False)); + return new NavigableLocation(async (_, _) => value); } } } diff --git a/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs b/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs index 026aafeb92c19..af84d4e22a275 100644 --- a/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs @@ -88,7 +88,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte context.RegisterRefactoring(CodeAction.Create( document.GetRequiredLanguageService().SortImportsDisplayStringWithoutAccelerator, - cancellationToken => Task.FromResult(document.WithSyntaxRoot(newRoot))), + async cancellationToken => document.WithSyntaxRoot(newRoot)), applicableToSpan: imports.GetContainedSpan()); } } diff --git a/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeCodeFixProvider.cs b/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeCodeFixProvider.cs index 416ee5dc0c44b..2e8b4b7f87f53 100644 --- a/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeCodeFixProvider.cs +++ b/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeCodeFixProvider.cs @@ -23,15 +23,13 @@ internal sealed class PreferFrameworkTypeCodeFixProvider() : SyntaxEditorBasedCo public sealed override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId]; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics[0]; if (diagnostic.Properties.ContainsKey(PreferFrameworkTypeConstants.PreferFrameworkType)) { RegisterCodeFix(context, FeaturesResources.Use_framework_type, nameof(FeaturesResources.Use_framework_type)); } - - return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs b/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs index 5a55c3ae91af3..5d2f29b895f1a 100644 --- a/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs +++ b/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs @@ -185,8 +185,8 @@ protected static Task CreateContentAsync( protected abstract bool GetBindableNodeForTokenIndicatingPossibleIndexerAccess(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found); protected abstract bool GetBindableNodeForTokenIndicatingMemberAccess(SyntaxToken token, out SyntaxToken found); - protected virtual Task GetOnTheFlyDocsInfoAsync(QuickInfoContext context, CancellationToken cancellationToken) - => Task.FromResult(null); + protected virtual async Task GetOnTheFlyDocsInfoAsync(QuickInfoContext context, CancellationToken cancellationToken) + => null; protected virtual string? GetNullabilityAnalysis(SemanticModel semanticModel, ISymbol symbol, SyntaxNode node, CancellationToken cancellationToken) => null; diff --git a/src/Features/Core/Portable/QuickInfo/QuickInfoService.cs b/src/Features/Core/Portable/QuickInfo/QuickInfoService.cs index 816669d75b6a7..95c1fcec88326 100644 --- a/src/Features/Core/Portable/QuickInfo/QuickInfoService.cs +++ b/src/Features/Core/Portable/QuickInfo/QuickInfoService.cs @@ -40,12 +40,12 @@ internal QuickInfoService() return GetQuickInfoAsync(document, position, SymbolDescriptionOptions.Default, cancellationToken); } - internal virtual Task GetQuickInfoAsync( + internal virtual async Task GetQuickInfoAsync( Document document, int position, SymbolDescriptionOptions options, CancellationToken cancellationToken) { - return SpecializedTasks.Null(); + return null; } } diff --git a/src/Features/Core/Portable/SemanticSearch/SearchCompilationFailureDefinitionItem.cs b/src/Features/Core/Portable/SemanticSearch/SearchCompilationFailureDefinitionItem.cs index cc0ab05fae1a8..14f1a1e579ae3 100644 --- a/src/Features/Core/Portable/SemanticSearch/SearchCompilationFailureDefinitionItem.cs +++ b/src/Features/Core/Portable/SemanticSearch/SearchCompilationFailureDefinitionItem.cs @@ -33,7 +33,7 @@ internal sealed class SearchCompilationFailureDefinitionItem(QueryCompilationErr { internal override bool IsExternal => false; - public override Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) - => Task.FromResult(null); + public override async Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) + => null; } diff --git a/src/Features/Core/Portable/SemanticSearch/SearchExceptionDefinitionItem.cs b/src/Features/Core/Portable/SemanticSearch/SearchExceptionDefinitionItem.cs index 927ec6da8ae43..ecff91bc9059c 100644 --- a/src/Features/Core/Portable/SemanticSearch/SearchExceptionDefinitionItem.cs +++ b/src/Features/Core/Portable/SemanticSearch/SearchExceptionDefinitionItem.cs @@ -37,7 +37,7 @@ .. stackTrace { internal override bool IsExternal => false; - public override Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) - => Task.FromResult(null); + public override async Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) + => null; } diff --git a/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeCodeFixProvider.cs b/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeCodeFixProvider.cs index 1f99311067ec3..9413925b75df2 100644 --- a/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeCodeFixProvider.cs +++ b/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeCodeFixProvider.cs @@ -27,10 +27,9 @@ internal abstract partial class AbstractSimplifyThisOrMeCodeFixProvider FixableDiagnosticIds { get; } = [IDEDiagnosticIds.RemoveThisOrMeQualificationDiagnosticId]; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, GetTitle(), IDEDiagnosticIds.RemoveThisOrMeQualificationDiagnosticId); - return Task.CompletedTask; } protected sealed override async Task FixAllAsync( diff --git a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractConditionalBlockSnippetProvider.cs b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractConditionalBlockSnippetProvider.cs index a94185d9ffbd7..8e5f1c24c6418 100644 --- a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractConditionalBlockSnippetProvider.cs +++ b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractConditionalBlockSnippetProvider.cs @@ -21,13 +21,13 @@ internal abstract class AbstractConditionalBlockSnippetProvider type.SpecialType == SpecialType.System_Boolean; - protected sealed override ValueTask> GetPlaceHolderLocationsListAsync( + protected sealed override async ValueTask> GetPlaceHolderLocationsListAsync( Document document, TStatementSyntax node, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { if (ConstructedFromInlineExpression) - return new([]); + return []; var condition = GetCondition(node); - return new([new SnippetPlaceholder(condition.ToString(), condition.SpanStart)]); + return [new SnippetPlaceholder(condition.ToString(), condition.SpanStart)]; } } diff --git a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractLockSnippetProvider.cs b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractLockSnippetProvider.cs index 006fc5a0318dd..85a0ec8cee204 100644 --- a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractLockSnippetProvider.cs +++ b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractLockSnippetProvider.cs @@ -12,10 +12,10 @@ namespace Microsoft.CodeAnalysis.Snippets.SnippetProviders; internal abstract class AbstractLockSnippetProvider : AbstractStatementSnippetProvider where TLockStatementSyntax : SyntaxNode { - protected sealed override Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) + protected sealed override async Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var statement = generator.LockStatement(generator.ThisExpression(), statements: []); - return Task.FromResult(new TextChange(TextSpan.FromBounds(position, position), statement.NormalizeWhitespace().ToFullString())); + return new TextChange(TextSpan.FromBounds(position, position), statement.NormalizeWhitespace().ToFullString()); } } diff --git a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractMainMethodSnippetProvider.cs b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractMainMethodSnippetProvider.cs index b6f9b706a11a9..39285b9772b4a 100644 --- a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractMainMethodSnippetProvider.cs +++ b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractMainMethodSnippetProvider.cs @@ -19,7 +19,7 @@ internal abstract class AbstractMainMethodSnippetProvider GenerateInnerStatements(SyntaxGenerator generator); - protected sealed override Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) + protected sealed override async Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var method = generator.MethodDeclaration( @@ -31,6 +31,6 @@ protected sealed override Task GenerateSnippetTextChangeAsync(Docume modifiers: DeclarationModifiers.Static, statements: GenerateInnerStatements(generator)); - return Task.FromResult(new TextChange(TextSpan.FromBounds(position, position), method.NormalizeWhitespace().ToFullString())); + return new TextChange(TextSpan.FromBounds(position, position), method.NormalizeWhitespace().ToFullString()); } } diff --git a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractSnippetProvider.cs b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractSnippetProvider.cs index 2e7531c518669..035819b9fe535 100644 --- a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractSnippetProvider.cs +++ b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractSnippetProvider.cs @@ -48,9 +48,9 @@ internal abstract class AbstractSnippetProvider : ISnippetProvid /// /// Method to find the locations that must be renamed and where tab stops must be inserted into the snippet. /// - protected virtual ValueTask> GetPlaceHolderLocationsListAsync( + protected virtual async ValueTask> GetPlaceHolderLocationsListAsync( Document document, TSnippetSyntax node, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) - => new([]); + => []; public bool IsValidSnippetLocation(SnippetContext context, CancellationToken cancellationToken) { @@ -222,8 +222,8 @@ private async Task AnnotateNodesToReformatAsync( reformatSnippetNode.WithAdditionalAnnotations(FindSnippetAnnotation, Simplifier.Annotation, Formatter.Annotation)); } - protected virtual ValueTask AdjustSnippetExpressionAsync(Document document, TSnippetSyntax snippetExpressionNode, CancellationToken cancellationToken) - => new(snippetExpressionNode); + protected virtual async ValueTask AdjustSnippetExpressionAsync(Document document, TSnippetSyntax snippetExpressionNode, CancellationToken cancellationToken) + => snippetExpressionNode; protected virtual TSnippetSyntax? FindAddedSnippetSyntaxNode(SyntaxNode root, int position) => root.FindNode(TextSpan.FromBounds(position, position), getInnermostNodeForTie: true) as TSnippetSyntax; @@ -244,6 +244,6 @@ private async Task AddIndentationToDocumentAsync(Document document, Ca return await AddIndentationToDocumentAsync(document, snippet, cancellationToken).ConfigureAwait(false); } - protected virtual Task AddIndentationToDocumentAsync(Document document, TSnippetSyntax snippet, CancellationToken cancellationToken) - => Task.FromResult(document); + protected virtual async Task AddIndentationToDocumentAsync(Document document, TSnippetSyntax snippet, CancellationToken cancellationToken) + => document; } diff --git a/src/Features/Core/Portable/SplitOrMergeIfStatements/AbstractSplitIfStatementCodeRefactoringProvider.cs b/src/Features/Core/Portable/SplitOrMergeIfStatements/AbstractSplitIfStatementCodeRefactoringProvider.cs index fdcf3a12e5173..f8fb871877d99 100644 --- a/src/Features/Core/Portable/SplitOrMergeIfStatements/AbstractSplitIfStatementCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/SplitOrMergeIfStatements/AbstractSplitIfStatementCodeRefactoringProvider.cs @@ -22,7 +22,7 @@ internal abstract class AbstractSplitIfStatementCodeRefactoringProvider : CodeRe protected abstract CodeAction CreateCodeAction(Func> createChangedDocument, string ifKeywordText); - protected abstract Task GetChangedRootAsync( + protected abstract ValueTask GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, diff --git a/src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs b/src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs index 49e37866eaad9..bb00eccfedf33 100644 --- a/src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs @@ -50,7 +50,7 @@ protected sealed override CodeAction CreateCodeAction(Func GetChangedRootAsync( + protected sealed override async ValueTask GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, diff --git a/src/Features/Core/Portable/SplitOrMergeIfStatements/Nested/AbstractSplitIntoNestedIfStatementsCodeRefactoringProvider.cs b/src/Features/Core/Portable/SplitOrMergeIfStatements/Nested/AbstractSplitIntoNestedIfStatementsCodeRefactoringProvider.cs index cedc4f34f2a5a..0f3655e8ac56b 100644 --- a/src/Features/Core/Portable/SplitOrMergeIfStatements/Nested/AbstractSplitIntoNestedIfStatementsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/SplitOrMergeIfStatements/Nested/AbstractSplitIntoNestedIfStatementsCodeRefactoringProvider.cs @@ -37,7 +37,7 @@ protected sealed override CodeAction CreateCodeAction(Func GetChangedRootAsync( + protected sealed override async ValueTask GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, @@ -53,7 +53,6 @@ protected sealed override Task GetChangedRootAsync( var innerIfStatement = ifGenerator.WithCondition(ifGenerator.ToIfStatement(ifOrElseIf), rightCondition); var outerIfOrElseIf = ifGenerator.WithCondition(ifGenerator.WithStatementInBlock(ifOrElseIf, innerIfStatement), leftCondition); - return Task.FromResult( - root.ReplaceNode(ifOrElseIf, outerIfOrElseIf.WithAdditionalAnnotations(Formatter.Annotation))); + return root.ReplaceNode(ifOrElseIf, outerIfOrElseIf.WithAdditionalAnnotations(Formatter.Annotation)); } } diff --git a/src/Features/Core/Portable/StackTraceExplorer/StackFrameMethodSymbolResolver.cs b/src/Features/Core/Portable/StackTraceExplorer/StackFrameMethodSymbolResolver.cs index 877911305c84e..f8bbad417b95b 100644 --- a/src/Features/Core/Portable/StackTraceExplorer/StackFrameMethodSymbolResolver.cs +++ b/src/Features/Core/Portable/StackTraceExplorer/StackFrameMethodSymbolResolver.cs @@ -11,7 +11,7 @@ namespace Microsoft.CodeAnalysis.StackTraceExplorer; internal sealed class StackFrameMethodSymbolResolver : AbstractStackTraceSymbolResolver { - public override Task TryGetBestMatchAsync( + public override async Task TryGetBestMatchAsync( Project project, INamedTypeSymbol type, StackFrameSimpleNameNode methodNode, @@ -27,6 +27,6 @@ internal sealed class StackFrameMethodSymbolResolver : AbstractStackTraceSymbolR .Where(m => m.Name == methodName); var match = TryGetBestMatch(candidateMethods, methodTypeArguments, methodArguments); - return Task.FromResult(match); + return match; } } diff --git a/src/Features/Core/Portable/StackTraceExplorer/StackTraceAnalyzer.cs b/src/Features/Core/Portable/StackTraceExplorer/StackTraceAnalyzer.cs index e3198d3e6fa29..6346902a87777 100644 --- a/src/Features/Core/Portable/StackTraceExplorer/StackTraceAnalyzer.cs +++ b/src/Features/Core/Portable/StackTraceExplorer/StackTraceAnalyzer.cs @@ -23,10 +23,10 @@ internal static class StackTraceAnalyzer /// private static readonly ImmutableArray s_parsers = [new DotnetStackFrameParser(), new VSDebugCallstackParser(), new DefaultStackParser()]; - public static Task AnalyzeAsync(string callstack, CancellationToken cancellationToken) + public static async Task AnalyzeAsync(string callstack, CancellationToken cancellationToken) { var result = new StackTraceAnalysisResult(callstack, Parse(callstack, cancellationToken)); - return Task.FromResult(result); + return result; } private static ImmutableArray Parse(string callstack, CancellationToken cancellationToken) diff --git a/src/Features/Core/Portable/SymbolMapping/SymbolMappingServiceFactory.cs b/src/Features/Core/Portable/SymbolMapping/SymbolMappingServiceFactory.cs index 94c39c7355c19..7c7da96a65d28 100644 --- a/src/Features/Core/Portable/SymbolMapping/SymbolMappingServiceFactory.cs +++ b/src/Features/Core/Portable/SymbolMapping/SymbolMappingServiceFactory.cs @@ -33,6 +33,6 @@ public async Task MapSymbolAsync(Document document, SymbolK return null; } - public Task MapSymbolAsync(Document document, ISymbol symbol, CancellationToken cancellationToken) - => Task.FromResult(new SymbolMappingResult(document.Project, symbol)); + public async Task MapSymbolAsync(Document document, ISymbol symbol, CancellationToken cancellationToken) + => new SymbolMappingResult(document.Project, symbol); } diff --git a/src/Features/Core/Portable/SymbolSearch/SymbolSearchUpdateNoOpEngine.cs b/src/Features/Core/Portable/SymbolSearch/SymbolSearchUpdateNoOpEngine.cs index eef3b039283ec..1ba86fb8f3f80 100644 --- a/src/Features/Core/Portable/SymbolSearch/SymbolSearchUpdateNoOpEngine.cs +++ b/src/Features/Core/Portable/SymbolSearch/SymbolSearchUpdateNoOpEngine.cs @@ -18,14 +18,14 @@ public void Dispose() // Nothing to do for the no-op version. } - public ValueTask> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) - => ValueTask.FromResult(ImmutableArray.Empty); + public async ValueTask> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) + => ImmutableArray.Empty; - public ValueTask> FindPackagesAsync(string source, TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) - => ValueTask.FromResult(ImmutableArray.Empty); + public async ValueTask> FindPackagesAsync(string source, TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) + => ImmutableArray.Empty; - public ValueTask> FindReferenceAssembliesAsync(TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) - => ValueTask.FromResult(ImmutableArray.Empty); + public async ValueTask> FindReferenceAssembliesAsync(TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) + => ImmutableArray.Empty; public ValueTask UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory, CancellationToken cancellationToken) => default; diff --git a/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.Update.cs b/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.Update.cs index 3cdbe883397d3..389c9eb84d4ba 100644 --- a/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.Update.cs +++ b/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.Update.cs @@ -62,7 +62,7 @@ internal sealed partial class SymbolSearchUpdateEngine /// Currently used only in tests so we can shutdown gracefully. In normal VS+OOP scenarios /// we don't care about this and we just get torn down when the OOP process goes down. /// - public ValueTask UpdateContinuouslyAsync(string source, string localSettingsDirectory, CancellationToken cancellationToken) + public async ValueTask UpdateContinuouslyAsync(string source, string localSettingsDirectory, CancellationToken cancellationToken) { // Only the first thread to try to update this source should succeed // and cause us to actually begin the update loop. @@ -72,12 +72,12 @@ public ValueTask UpdateContinuouslyAsync(string source, string localSettingsDire if (ourSentinel != currentSentinel) { // We already have an update loop for this source. Nothing for us to do. - return default; + return; } // We were the first ones to try to update this source. Spawn off a task to do // the updating. - return new Updater(this, source, localSettingsDirectory).UpdateInBackgroundAsync(cancellationToken); + await new Updater(this, source, localSettingsDirectory).UpdateInBackgroundAsync(cancellationToken).ConfigureAwait(false); } private static void LogInfo(string text) diff --git a/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs b/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs index 42d372b04cb1f..64b9608db3c11 100644 --- a/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs +++ b/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs @@ -111,7 +111,7 @@ public ValueTask> FindReferenceAssemblie cancellationToken); } - public ValueTask> FindPackageOrReferenceAssembliesAsync( + public async ValueTask> FindPackageOrReferenceAssembliesAsync( string source, TypeQuery typeQuery, NamespaceQuery namespaceQuery, @@ -121,7 +121,7 @@ public ValueTask> FindPackageOrReferenceAssembliesAsync< { // Check if we don't have a database to search. if (!_sourceToDatabase.TryGetValue(source, out var databaseWrapper)) - return ValueTask.FromResult(ImmutableArray.Empty); + return ImmutableArray.Empty; var database = databaseWrapper.Database; @@ -129,7 +129,7 @@ public ValueTask> FindPackageOrReferenceAssembliesAsync< // never find anything named 'var'. if (searchName == "var") - return ValueTask.FromResult(ImmutableArray.Empty); + return ImmutableArray.Empty; var query = new MemberQuery(searchName, isFullSuffix: true, isFullNamespace: false); var symbols = new PartialArray(100); @@ -146,7 +146,7 @@ public ValueTask> FindPackageOrReferenceAssembliesAsync< } } - return ValueTask.FromResult(results.ToImmutableAndClear()); + return results.ToImmutableAndClear(); static IEnumerable FilterToViableSymbols( PartialArray symbols, NamespaceQuery namespaceQuery) @@ -173,13 +173,13 @@ static IEnumerable FilterToViableSymbols( } } - public ValueTask> FindPackagesWithAssemblyAsync( + public async ValueTask> FindPackagesWithAssemblyAsync( string source, string assemblyName, CancellationToken cancellationToken) { if (!_sourceToDatabase.TryGetValue(source, out var databaseWrapper)) { // Don't have a database to search. - return ValueTask.FromResult(ImmutableArray.Empty); + return ImmutableArray.Empty; } using var _ = ArrayBuilder.GetInstance(out var result); @@ -211,7 +211,7 @@ public ValueTask> FindPackagesWithAsse } } - return ValueTask.FromResult(result.ToImmutableAndClear()); + return result.ToImmutableAndClear(); } private static int GetRank(Symbol symbol) diff --git a/src/Features/Core/Portable/UseNamedArguments/AbstractUseNamedArgumentsCodeRefactoringProvider.cs b/src/Features/Core/Portable/UseNamedArguments/AbstractUseNamedArgumentsCodeRefactoringProvider.cs index 3a9ab3951b7be..cf3711d1d0a18 100644 --- a/src/Features/Core/Portable/UseNamedArguments/AbstractUseNamedArgumentsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/UseNamedArguments/AbstractUseNamedArgumentsCodeRefactoringProvider.cs @@ -132,7 +132,7 @@ public async Task ComputeRefactoringsAsync( } } - private Task AddNamedArgumentsAsync( + private async Task AddNamedArgumentsAsync( SyntaxNode root, Document document, TSimpleArgumentSyntax firstArgument, @@ -143,7 +143,7 @@ private Task AddNamedArgumentsAsync( var argumentList = (TArgumentListSyntax)firstArgument.Parent!; var newArgumentList = GetOrSynthesizeNamedArguments(parameters, argumentList, index, includingTrailingArguments); var newRoot = root.ReplaceNode(argumentList, newArgumentList); - return Task.FromResult(document.WithSyntaxRoot(newRoot)); + return document.WithSyntaxRoot(newRoot); } private TArgumentListSyntax GetOrSynthesizeNamedArguments( diff --git a/src/Features/Core/Portable/ValueTracking/ValueTracker.OperationCollector.cs b/src/Features/Core/Portable/ValueTracking/ValueTracker.OperationCollector.cs index 61d32f16b98b0..c24c630bb9e7d 100644 --- a/src/Features/Core/Portable/ValueTracking/ValueTracker.OperationCollector.cs +++ b/src/Features/Core/Portable/ValueTracking/ValueTracker.OperationCollector.cs @@ -108,7 +108,7 @@ private async Task VisitInvocationAsync(IInvocationOperation invocationOperation await TrackArgumentsAsync(invocationOperation.Arguments, cancellationToken).ConfigureAwait(false); } - private Task VisitReferenceAsync(IOperation operation, CancellationToken cancellationToken) + private async Task VisitReferenceAsync(IOperation operation, CancellationToken cancellationToken) { Debug.Assert(operation is ILocalReferenceOperation or @@ -122,23 +122,22 @@ IFieldReferenceOperation or { // Always add ref or out parameters to track as assignments since the values count as // assignments across method calls for the purposes of value tracking. - return AddOperationAsync(operation, argumentOperation.Parameter, cancellationToken); + await AddOperationAsync(operation, argumentOperation.Parameter, cancellationToken).ConfigureAwait(false); + } + else + { + // If the parameter is not a ref or out param, track the reference assignments that count + // as input to the argument being passed to the method. + await AddReferenceAsync(operation, cancellationToken).ConfigureAwait(false); } - - // If the parameter is not a ref or out param, track the reference assignments that count - // as input to the argument being passed to the method. - return AddReferenceAsync(operation, cancellationToken); } - - if (IsContainedIn(operation) || IsContainedIn(operation)) + else if (IsContainedIn(operation) || IsContainedIn(operation)) { // If the reference is part of a return operation or assignment operation we want to track where the values come from // since they contribute to the "output" of the method/assignment and are relavent for value tracking. - return AddReferenceAsync(operation, cancellationToken); + await AddReferenceAsync(operation, cancellationToken).ConfigureAwait(false); } - return Task.CompletedTask; - Task AddReferenceAsync(IOperation operation, CancellationToken cancellationToken) => operation switch { @@ -150,24 +149,24 @@ Task AddReferenceAsync(IOperation operation, CancellationToken cancellationToken }; } - private Task VisitLiteralAsync(ILiteralOperation literalOperation, CancellationToken cancellationToken) + private async Task VisitLiteralAsync(ILiteralOperation literalOperation, CancellationToken cancellationToken) { if (literalOperation.Type is null) { - return Task.CompletedTask; + return; } - return AddOperationAsync(literalOperation, literalOperation.Type, cancellationToken); + await AddOperationAsync(literalOperation, literalOperation.Type, cancellationToken).ConfigureAwait(false); } - private Task VisitReturnAsync(IReturnOperation returnOperation, CancellationToken cancellationToken) + private async Task VisitReturnAsync(IReturnOperation returnOperation, CancellationToken cancellationToken) { if (returnOperation.ReturnedValue is null) { - return Task.CompletedTask; + return; } - return VisitAsync(returnOperation.ReturnedValue, cancellationToken); + await VisitAsync(returnOperation.ReturnedValue, cancellationToken).ConfigureAwait(false); } private async Task AddOperationAsync(IOperation operation, ISymbol symbol, CancellationToken cancellationToken) diff --git a/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs b/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs index 02caaf4eeca29..a8c8c73534ab0 100644 --- a/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs +++ b/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs @@ -157,7 +157,7 @@ protected async Task GetIndentationAfterAsync( // Store the root so we don't just end up creating this code action again. _seenDocumentRoots.Add(formattedRoot); - return new WrapItemsAction(title, parentTitle, (_, _) => Task.FromResult(formattedDocument)); + return new WrapItemsAction(title, parentTitle, async (_, _) => formattedDocument); } private async Task FormatDocumentAsync( diff --git a/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs b/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs index 0473efa36bac4..920982571935a 100644 --- a/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs +++ b/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs @@ -119,14 +119,14 @@ protected override CompilationOptions CreateCompilationOptions() private static readonly TestComposition s_editorFeaturesOOPComposition = FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess); - protected override Task CreateWorkspaceImplAsync() + protected override async Task CreateWorkspaceImplAsync() { if (TestHost == TestHost.InProcess) - return base.CreateWorkspaceImplAsync(); + return await base.CreateWorkspaceImplAsync().ConfigureAwait(false); var hostServices = s_editorFeaturesOOPComposition.GetHostServices(); var workspace = new AdhocWorkspace(hostServices); - return Task.FromResult(workspace); + return workspace; } #endif } diff --git a/src/Features/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeRefactoringVerifier`1+Test.cs b/src/Features/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeRefactoringVerifier`1+Test.cs index e6a00a6496828..a49946d0db1af 100644 --- a/src/Features/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeRefactoringVerifier`1+Test.cs +++ b/src/Features/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeRefactoringVerifier`1+Test.cs @@ -106,14 +106,14 @@ protected override ParseOptions CreateParseOptions() private static readonly TestComposition s_editorFeaturesOOPComposition = FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess); - protected override Task CreateWorkspaceImplAsync() + protected override async Task CreateWorkspaceImplAsync() { if (TestHost == TestHost.InProcess) - return base.CreateWorkspaceImplAsync(); + return await base.CreateWorkspaceImplAsync().ConfigureAwait(false); var hostServices = s_editorFeaturesOOPComposition.GetHostServices(); var workspace = new AdhocWorkspace(hostServices); - return Task.FromResult(workspace); + return workspace; } #endif diff --git a/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs b/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs index 07690dcae04ce..ece9bc416c87d 100644 --- a/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs +++ b/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs @@ -97,8 +97,8 @@ private static async Task GetFixAllFixAsync( return await refactorAllProvider.GetRefactoringAsync(refactorAllContext).ConfigureAwait(false); } - protected override Task> GetDiagnosticsWorkerAsync(TTestWorkspace workspace, TestParameters parameters) - => SpecializedTasks.EmptyImmutableArray(); + protected override async Task> GetDiagnosticsWorkerAsync(TTestWorkspace workspace, TestParameters parameters) + => []; internal override async Task GetCodeRefactoringAsync( TTestWorkspace workspace, TestParameters parameters) diff --git a/src/Features/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs b/src/Features/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs index ae44dadd08e08..fdb081db59a53 100644 --- a/src/Features/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs +++ b/src/Features/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs @@ -166,9 +166,9 @@ public async Task> GetCachedDocumentDiagnosticsAsync( return diagnostics.ToImmutable(); } - protected virtual Task> GetDiagnosticsIntersectWithSpanAsync(Document document, IReadOnlyList diagnostics, TextSpan span, CancellationToken cancellationToken) + protected virtual async Task> GetDiagnosticsIntersectWithSpanAsync(Document document, IReadOnlyList diagnostics, TextSpan span, CancellationToken cancellationToken) { - return Task.FromResult(diagnostics.WhereAsArray(static (diagnostic, span) => diagnostic.Location.SourceSpan.IntersectsWith(span), span)); + return diagnostics.WhereAsArray(static (diagnostic, span) => diagnostic.Location.SourceSpan.IntersectsWith(span), span); } public async Task StartRefinementSessionAsync(Document oldDocument, Document newDocument, Diagnostic? primaryDiagnostic, CancellationToken cancellationToken) diff --git a/src/Features/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs b/src/Features/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs index ac005eb0be0e0..81e03e7dfded4 100644 --- a/src/Features/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs +++ b/src/Features/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs @@ -59,60 +59,58 @@ IDiagnosticsRefresher diagnosticsRefresher GenerateImplementationService = externalCSharpCopilotGenerateImplementationService; } - protected override Task> AnalyzeDocumentCoreAsync(Document document, TextSpan? span, string promptTitle, CancellationToken cancellationToken) + protected override async Task> AnalyzeDocumentCoreAsync(Document document, TextSpan? span, string promptTitle, CancellationToken cancellationToken) { if (AnalysisService is not null) - return AnalysisService.AnalyzeDocumentAsync(document, span, promptTitle, cancellationToken); + return await AnalysisService.AnalyzeDocumentAsync(document, span, promptTitle, cancellationToken).ConfigureAwait(false); - return Task.FromResult(ImmutableArray.Empty); + return ImmutableArray.Empty; } - protected override Task> GetAvailablePromptTitlesCoreAsync(Document document, CancellationToken cancellationToken) + protected override async Task> GetAvailablePromptTitlesCoreAsync(Document document, CancellationToken cancellationToken) { if (AnalysisService is not null) - return AnalysisService.GetAvailablePromptTitlesAsync(document, cancellationToken); + return await AnalysisService.GetAvailablePromptTitlesAsync(document, cancellationToken).ConfigureAwait(false); - return Task.FromResult(ImmutableArray.Empty); + return ImmutableArray.Empty; } - protected override Task> GetCachedDiagnosticsCoreAsync(Document document, string promptTitle, CancellationToken cancellationToken) + protected override async Task> GetCachedDiagnosticsCoreAsync(Document document, string promptTitle, CancellationToken cancellationToken) { if (AnalysisService is not null) - return AnalysisService.GetCachedDiagnosticsAsync(document, promptTitle, cancellationToken); + return await AnalysisService.GetCachedDiagnosticsAsync(document, promptTitle, cancellationToken).ConfigureAwait(false); - return Task.FromResult(ImmutableArray.Empty); + return ImmutableArray.Empty; } - protected override Task IsAvailableCoreAsync(CancellationToken cancellationToken) + protected override async Task IsAvailableCoreAsync(CancellationToken cancellationToken) { if (AnalysisService is not null) - return AnalysisService.IsAvailableAsync(cancellationToken); + return await AnalysisService.IsAvailableAsync(cancellationToken).ConfigureAwait(false); - return Task.FromResult(false); + return false; } - protected override Task StartRefinementSessionCoreAsync(Document oldDocument, Document newDocument, Diagnostic? primaryDiagnostic, CancellationToken cancellationToken) + protected override async Task StartRefinementSessionCoreAsync(Document oldDocument, Document newDocument, Diagnostic? primaryDiagnostic, CancellationToken cancellationToken) { if (AnalysisService is not null) - return AnalysisService.StartRefinementSessionAsync(oldDocument, newDocument, primaryDiagnostic, cancellationToken); - - return Task.CompletedTask; + await AnalysisService.StartRefinementSessionAsync(oldDocument, newDocument, primaryDiagnostic, cancellationToken).ConfigureAwait(false); } - protected override Task GetOnTheFlyDocsPromptCoreAsync(OnTheFlyDocsInfo onTheFlyDocsInfo, CancellationToken cancellationToken) + protected override async Task GetOnTheFlyDocsPromptCoreAsync(OnTheFlyDocsInfo onTheFlyDocsInfo, CancellationToken cancellationToken) { if (OnTheFlyDocsService is not null) - return OnTheFlyDocsService.GetOnTheFlyDocsPromptAsync(new CopilotOnTheFlyDocsInfoWrapper(onTheFlyDocsInfo), cancellationToken); + return await OnTheFlyDocsService.GetOnTheFlyDocsPromptAsync(new CopilotOnTheFlyDocsInfoWrapper(onTheFlyDocsInfo), cancellationToken).ConfigureAwait(false); - return Task.FromResult(string.Empty); + return string.Empty; } - protected override Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsResponseCoreAsync(string prompt, CancellationToken cancellationToken) + protected override async Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsResponseCoreAsync(string prompt, CancellationToken cancellationToken) { if (OnTheFlyDocsService is not null) - return OnTheFlyDocsService.GetOnTheFlyDocsResponseAsync(prompt, cancellationToken); + return await OnTheFlyDocsService.GetOnTheFlyDocsResponseAsync(prompt, cancellationToken).ConfigureAwait(false); - return Task.FromResult((string.Empty, false)); + return (string.Empty, false); } protected override async Task> GetDiagnosticsIntersectWithSpanAsync( @@ -135,20 +133,20 @@ protected override async Task> GetDiagnosticsIntersec return filteredDiagnostics.ToImmutable(); } - protected override Task IsFileExcludedCoreAsync(string filePath, CancellationToken cancellationToken) + protected override async Task IsFileExcludedCoreAsync(string filePath, CancellationToken cancellationToken) { if (AnalysisService is not null) - return AnalysisService.IsFileExcludedAsync(filePath, cancellationToken); + return await AnalysisService.IsFileExcludedAsync(filePath, cancellationToken).ConfigureAwait(false); - return Task.FromResult(false); + return false; } - protected override Task<(Dictionary? responseDictionary, bool isQuotaExceeded)> GetDocumentationCommentCoreAsync(DocumentationCommentProposal proposal, CancellationToken cancellationToken) + protected override async Task<(Dictionary? responseDictionary, bool isQuotaExceeded)> GetDocumentationCommentCoreAsync(DocumentationCommentProposal proposal, CancellationToken cancellationToken) { if (GenerateDocumentationService is not null) - return GenerateDocumentationService.GetDocumentationCommentAsync(new CopilotDocumentationCommentProposalWrapper(proposal), cancellationToken); + return await GenerateDocumentationService.GetDocumentationCommentAsync(new CopilotDocumentationCommentProposalWrapper(proposal), cancellationToken).ConfigureAwait(false); - return Task.FromResult<(Dictionary?, bool)>((null, false)); + return (null, false); } protected override bool IsImplementNotImplementedExceptionsAvailableCore() diff --git a/src/Features/ExternalAccess/Copilot/Internal/Completion/CSharpContextProviderService.cs b/src/Features/ExternalAccess/Copilot/Internal/Completion/CSharpContextProviderService.cs index 5915edf57088a..d00004a66d1ac 100644 --- a/src/Features/ExternalAccess/Copilot/Internal/Completion/CSharpContextProviderService.cs +++ b/src/Features/ExternalAccess/Copilot/Internal/Completion/CSharpContextProviderService.cs @@ -27,12 +27,10 @@ public IAsyncEnumerable GetContextItemsAsync(Document document, in static async (provider, callback, args, cancellationToken) => await provider.ProvideContextItemsAsync( args.document, args.position, args.activeExperiments, - (items, cancellationToken) => + async (items, cancellationToken) => { foreach (var item in items) callback(item); - - return default; }, cancellationToken).ConfigureAwait(false), args: (document, position, activeExperiments), cancellationToken); diff --git a/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/CopilotSemanticSearchQueryExecutor.cs b/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/CopilotSemanticSearchQueryExecutor.cs index 429e9bb145610..48c9fe2e44ed1 100644 --- a/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/CopilotSemanticSearchQueryExecutor.cs +++ b/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/CopilotSemanticSearchQueryExecutor.cs @@ -34,8 +34,8 @@ private sealed class ResultsObserver(CancellationTokenSource cancellationSource, /// /// We only use symbol display names, classification is not relevant. /// - public ValueTask GetClassificationOptionsAsync(LanguageServices language, CancellationToken cancellationToken) - => new(ClassificationOptions.Default); + public async ValueTask GetClassificationOptionsAsync(LanguageServices language, CancellationToken cancellationToken) + => ClassificationOptions.Default; public ValueTask AddItemsAsync(int itemCount, CancellationToken cancellationToken) => ValueTask.CompletedTask; @@ -43,14 +43,13 @@ public ValueTask AddItemsAsync(int itemCount, CancellationToken cancellationToke public ValueTask ItemsCompletedAsync(int itemCount, CancellationToken cancellationToken) => ValueTask.CompletedTask; - public ValueTask OnUserCodeExceptionAsync(UserCodeExceptionInfo exception, CancellationToken cancellationToken) + public async ValueTask OnUserCodeExceptionAsync(UserCodeExceptionInfo exception, CancellationToken cancellationToken) { RuntimeException ??= $"{exception.TypeName.ToVisibleDisplayString(includeLeftToRightMarker: false)}: {exception.Message}{Environment.NewLine}{exception.StackTrace.ToVisibleDisplayString(includeLeftToRightMarker: false)}"; cancellationSource.Cancel(); - return ValueTask.CompletedTask; } - public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) + public async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { if (!ImmutableInterlocked.Update(ref _results, list => list.Count == resultCountLimit ? list : list.Add(definition.NameDisplayParts.ToVisibleDisplayString(includeLeftToRightMarker: false)))) @@ -58,8 +57,6 @@ public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationT LimitReached = true; cancellationSource.Cancel(); } - - return ValueTask.CompletedTask; } public ValueTask OnDocumentUpdatedAsync(DocumentId documentId, ImmutableArray changes, CancellationToken cancellationToken) diff --git a/src/Features/ExternalAccess/Copilot/SemanticSearch/CopilotSemanticSearchUtilities.cs b/src/Features/ExternalAccess/Copilot/SemanticSearch/CopilotSemanticSearchUtilities.cs index 81ff0b2f59772..0e4219cb63f18 100644 --- a/src/Features/ExternalAccess/Copilot/SemanticSearch/CopilotSemanticSearchUtilities.cs +++ b/src/Features/ExternalAccess/Copilot/SemanticSearch/CopilotSemanticSearchUtilities.cs @@ -55,12 +55,10 @@ private sealed class Progress(Action callback) : IStreamingFi public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => ValueTask.CompletedTask; public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) => ValueTask.CompletedTask; - public ValueTask OnReferencesFoundAsync(ImmutableArray<(SymbolGroup group, ISymbol symbol, ReferenceLocation location)> references, CancellationToken cancellationToken) + public async ValueTask OnReferencesFoundAsync(ImmutableArray<(SymbolGroup group, ISymbol symbol, ReferenceLocation location)> references, CancellationToken cancellationToken) { foreach (var (_, _, location) in references) callback(location); - - return ValueTask.CompletedTask; } public IStreamingProgressTracker ProgressTracker diff --git a/src/Features/ExternalAccess/HotReload/Api/HotReloadService.cs b/src/Features/ExternalAccess/HotReload/Api/HotReloadService.cs index da8d623383977..ba0885b6b4859 100644 --- a/src/Features/ExternalAccess/HotReload/Api/HotReloadService.cs +++ b/src/Features/ExternalAccess/HotReload/Api/HotReloadService.cs @@ -18,11 +18,11 @@ internal sealed class HotReloadService(SolutionServices services, Func>> capabilitiesProvider) : IManagedHotReloadService { - public ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) - => ValueTask.FromResult(ImmutableArray.Empty); + public async ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) + => ImmutableArray.Empty; - public ValueTask GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) - => ValueTask.FromResult(new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.Available)); + public async ValueTask GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) + => new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.Available); public ValueTask> GetCapabilitiesAsync(CancellationToken cancellationToken) => capabilitiesProvider(); @@ -129,14 +129,14 @@ public readonly struct Updates } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = - (_, _, _) => ValueTask.FromResult(ImmutableArray.Empty); + async (_, _, _) => ImmutableArray.Empty; private readonly IEditAndContinueService _encService = services.GetRequiredService().Service; private DebuggingSessionId _sessionId; public HotReloadService(HostWorkspaceServices services, ImmutableArray capabilities) - : this(services.SolutionServices, () => ValueTask.FromResult(AddImplicitDotNetCapabilities(capabilities))) + : this(services.SolutionServices, async () => AddImplicitDotNetCapabilities(capabilities)) { } diff --git a/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs b/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs index 61914cfd87225..92948008cf2eb 100644 --- a/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs +++ b/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs @@ -2654,7 +2654,7 @@ public async Task Project_Add_BinaryAlreadyLoaded() var trackedActiveSpans = ImmutableArray.Create( new ActiveStatementSpan(new ActiveStatementId(0), activeLineSpanB1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.LeafFrame)); - var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(documentB2, (_, _, _) => new(trackedActiveSpans), CancellationToken.None); + var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(documentB2, async (_, _, _) => trackedActiveSpans, CancellationToken.None); // TODO: https://github.com/dotnet/roslyn/issues/79423 // AssertEx.Equal(trackedActiveSpans, currentSpans); Assert.Empty(currentSpans); @@ -4590,7 +4590,7 @@ public async Task ActiveStatements() var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); - var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); + var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, async (_, _, _) => trackedActiveSpans1, CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); // change the source (valid edit): @@ -4602,7 +4602,7 @@ public async Task ActiveStatements() var activeStatementSpan22 = new ActiveStatementSpan(new ActiveStatementId(1), activeLineSpan22, ActiveStatementFlags.LeafFrame); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); - currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); + currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, async (_, _, _) => trackedActiveSpans2, CancellationToken.None); AssertEx.Equal([adjustedActiveLineSpan1, adjustedActiveLineSpan2], currentSpans.Select(s => s.LineSpan)); } @@ -4666,7 +4666,7 @@ public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSy var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: - var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTask.FromResult(baseSpans), CancellationToken.None); + var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, async (_, _, _) => baseSpans, CancellationToken.None); AssertEx.Equal([activeLineSpan11, activeLineSpan12], currentSpans.Select(s => s.LineSpan)); } diff --git a/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs b/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs index dd97b08c68add..219e5807487e8 100644 --- a/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs +++ b/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs @@ -113,11 +113,11 @@ await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution var activeSpans1 = ImmutableArray.Create( new ActiveStatementSpan(new ActiveStatementId(0), new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)), ActiveStatementFlags.NonLeafFrame, documentId)); - var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, path, cancellationToken) => + var activeStatementSpanProvider = new ActiveStatementSpanProvider(async (documentId, path, cancellationToken) => { Assert.Equal(documentId, documentId); Assert.Equal("test.cs", path); - return new(activeSpans1); + return activeSpans1; }); var diagnosticDescriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.AddingTypeRuntimeCapabilityRequired); diff --git a/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs b/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs index aa12537213bfb..b5006c3a395e2 100644 --- a/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs +++ b/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs @@ -22,6 +22,6 @@ internal sealed class MockServiceBroker : IServiceBroker public ValueTask GetPipeAsync(ServiceMoniker serviceMoniker, ServiceActivationOptions options = default, CancellationToken cancellationToken = default) => throw new NotImplementedException(); - public ValueTask GetProxyAsync(ServiceRpcDescriptor serviceDescriptor, ServiceActivationOptions options = default, CancellationToken cancellationToken = default) where T : class - => ValueTask.FromResult((T?)(CreateService ?? throw new NotImplementedException()).Invoke(typeof(T))); + public async ValueTask GetProxyAsync(ServiceRpcDescriptor serviceDescriptor, ServiceActivationOptions options = default, CancellationToken cancellationToken = default) where T : class + => (T?)(CreateService ?? throw new NotImplementedException()).Invoke(typeof(T)); } diff --git a/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs b/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs index 12904badeb6c6..c76816b4d1544 100644 --- a/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs +++ b/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs @@ -38,7 +38,7 @@ public abstract class EditAndContinueWorkspaceTestBase : TestBase, IDisposable private protected static readonly Regex s_timePropertiesRegex = new("[|](EmitDifferenceMilliseconds|TotalAnalysisMilliseconds)=[0-9]+"); private protected static readonly ActiveStatementSpanProvider s_noActiveSpans = - (_, _, _) => new([]); + async (_, _, _) => []; private protected const TargetFramework DefaultTargetFramework = TargetFramework.NetLatest; diff --git a/src/Features/TestUtilities/EditAndContinue/MockActiveStatementSpanProvider.cs b/src/Features/TestUtilities/EditAndContinue/MockActiveStatementSpanProvider.cs index 9060ea835fbb8..d28c4fe771abc 100644 --- a/src/Features/TestUtilities/EditAndContinue/MockActiveStatementSpanProvider.cs +++ b/src/Features/TestUtilities/EditAndContinue/MockActiveStatementSpanProvider.cs @@ -14,9 +14,9 @@ internal sealed class MockActiveStatementSpanProvider : IActiveStatementSpanFact public Func, ImmutableArray>>? GetBaseActiveStatementSpansImpl; public Func>? GetAdjustedActiveStatementSpansImpl; - public ValueTask>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) - => new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds)); + public async ValueTask>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) + => (GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds); - public ValueTask> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) - => new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); + public async ValueTask> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) + => (GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider); } diff --git a/src/Features/TestUtilities/EditAndContinue/MockEditAndContinueService.cs b/src/Features/TestUtilities/EditAndContinue/MockEditAndContinueService.cs index b585a1f4cd11c..cd85df62e01c5 100644 --- a/src/Features/TestUtilities/EditAndContinue/MockEditAndContinueService.cs +++ b/src/Features/TestUtilities/EditAndContinue/MockEditAndContinueService.cs @@ -39,20 +39,20 @@ public void CommitSolutionUpdate(DebuggingSessionId sessionId) public void DiscardSolutionUpdate(DebuggingSessionId sessionId) => DiscardSolutionUpdateImpl?.Invoke(); - public ValueTask EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ImmutableDictionary runningProjects, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) - => new((EmitSolutionUpdateImpl ?? throw new NotImplementedException()).Invoke(solution, runningProjects, activeStatementSpanProvider)); + public async ValueTask EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ImmutableDictionary runningProjects, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) + => (EmitSolutionUpdateImpl ?? throw new NotImplementedException()).Invoke(solution, runningProjects, activeStatementSpanProvider); public void EndDebuggingSession(DebuggingSessionId sessionId) => EndDebuggingSessionImpl?.Invoke(); - public ValueTask>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) - => new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds)); + public async ValueTask>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) + => (GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds); - public ValueTask> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) - => new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); + public async ValueTask> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) + => (GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider); - public ValueTask> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) - => new((GetDocumentDiagnosticsImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); + public async ValueTask> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) + => (GetDocumentDiagnosticsImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider); public void OnSourceFileUpdated(Document document) => OnSourceFileUpdatedImpl?.Invoke(document); diff --git a/src/Features/TestUtilities/EditAndContinue/MockManagedEditAndContinueDebuggerService.cs b/src/Features/TestUtilities/EditAndContinue/MockManagedEditAndContinueDebuggerService.cs index 207fa76880dde..aff02e6e57c57 100644 --- a/src/Features/TestUtilities/EditAndContinue/MockManagedEditAndContinueDebuggerService.cs +++ b/src/Features/TestUtilities/EditAndContinue/MockManagedEditAndContinueDebuggerService.cs @@ -19,26 +19,26 @@ internal sealed class MockManagedEditAndContinueDebuggerService : IManagedHotRel public Func>? GetActiveStatementsImpl; public Func>? GetCapabilitiesImpl; - public ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) - => ValueTask.FromResult(GetActiveStatementsImpl?.Invoke() ?? []); + public async ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) + => GetActiveStatementsImpl?.Invoke() ?? []; - public ValueTask GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken) + public async ValueTask GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken) { if (IsEditAndContinueAvailable != null) { - return ValueTask.FromResult(IsEditAndContinueAvailable(mvid)); + return IsEditAndContinueAvailable(mvid); } if (LoadedModules != null) { - return ValueTask.FromResult(LoadedModules.TryGetValue(mvid, out var result) ? result : new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.ModuleNotLoaded)); + return LoadedModules.TryGetValue(mvid, out var result) ? result : new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.ModuleNotLoaded); } throw new NotImplementedException(); } - public ValueTask> GetCapabilitiesAsync(CancellationToken cancellationToken) - => ValueTask.FromResult(GetCapabilitiesImpl?.Invoke() ?? ["Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"]); + public async ValueTask> GetCapabilitiesAsync(CancellationToken cancellationToken) + => GetCapabilitiesImpl?.Invoke() ?? ["Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"]; public ValueTask PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken) => ValueTask.CompletedTask; diff --git a/src/Features/TestUtilities/EditAndContinue/MockPdbMatchingSourceTextProvider.cs b/src/Features/TestUtilities/EditAndContinue/MockPdbMatchingSourceTextProvider.cs index c40e896847a2f..fd90c731b2d0a 100644 --- a/src/Features/TestUtilities/EditAndContinue/MockPdbMatchingSourceTextProvider.cs +++ b/src/Features/TestUtilities/EditAndContinue/MockPdbMatchingSourceTextProvider.cs @@ -15,6 +15,6 @@ internal sealed class MockPdbMatchingSourceTextProvider : IPdbMatchingSourceText { public Func, SourceHashAlgorithm, string?>? TryGetMatchingSourceTextImpl { get; set; } - public ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) - => ValueTask.FromResult(TryGetMatchingSourceTextImpl?.Invoke(filePath, requiredChecksum, checksumAlgorithm)); + public async ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) + => TryGetMatchingSourceTextImpl?.Invoke(filePath, requiredChecksum, checksumAlgorithm); } diff --git a/src/Features/TestUtilities/Options/TestOptionsProvider.cs b/src/Features/TestUtilities/Options/TestOptionsProvider.cs index f93921b093aa5..3851691431333 100644 --- a/src/Features/TestUtilities/Options/TestOptionsProvider.cs +++ b/src/Features/TestUtilities/Options/TestOptionsProvider.cs @@ -13,8 +13,8 @@ internal static class TestOptionsProvider { internal sealed class Provider(TOptions options) : OptionsProvider { - public ValueTask GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTask.FromResult(options); + public async ValueTask GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) + => options; } public static OptionsProvider Create(TOptions options) diff --git a/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs b/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs index d2e7cc11cf33a..bcd4c4934979f 100644 --- a/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs +++ b/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs @@ -58,11 +58,10 @@ public void Dispose() (_visualDiagnosticsLanguageService as IDisposable)?.Dispose(); } - public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { _cancellationToken = cancellationToken; _taskCompletionSource.TrySetResult(true); - return Task.CompletedTask; } public void OnServiceBrokerInitialized(IServiceBroker serviceBroker) diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs index 6d0590087b5fc..4f35f5c488218 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs @@ -118,21 +118,17 @@ private sealed class DynamicCapabilitiesRpcTarget public readonly ConcurrentDictionary Registrations = new(); [JsonRpcMethod("client/registerCapability", UseSingleObjectParameterDeserialization = true)] - public Task RegisterCapabilityAsync(RegistrationParams registrationParams, CancellationToken _) + public async Task RegisterCapabilityAsync(RegistrationParams registrationParams, CancellationToken _) { foreach (var registration in registrationParams.Registrations) Assert.True(Registrations.TryAdd(registration.Id, registration)); - - return Task.CompletedTask; } [JsonRpcMethod("client/unregisterCapability", UseSingleObjectParameterDeserialization = true)] - public Task UnregisterCapabilityAsync(UnregistrationParams unregistrationParams, CancellationToken _) + public async Task UnregisterCapabilityAsync(UnregistrationParams unregistrationParams, CancellationToken _) { foreach (var unregistration in unregistrationParams.Unregistrations) Assert.True(Registrations.TryRemove(unregistration.Id, out var _)); - - return Task.CompletedTask; } } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs index 088d183bc6701..33898cc63fad4 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs @@ -42,7 +42,7 @@ internal static async Task CreateAsync(ExportProvider container.ProfferIntrinsicService( FrameworkServices.Authorization, new ServiceRegistration(VisualStudio.Shell.ServiceBroker.ServiceAudience.Local, null, allowGuestClients: true), - (moniker, options, serviceBroker, cancellationToken) => new(new NoOpAuthorizationService())); + async (moniker, options, serviceBroker, cancellationToken) => new NoOpAuthorizationService()); var mefServiceBroker = exportProvider.GetExportedValue(); mefServiceBroker.SetContainer(container); @@ -62,14 +62,14 @@ private class NoOpAuthorizationService : IAuthorizationService public event EventHandler? AuthorizationChanged; - public ValueTask CheckAuthorizationAsync(ProtectedOperation operation, CancellationToken cancellationToken = default) + public async ValueTask CheckAuthorizationAsync(ProtectedOperation operation, CancellationToken cancellationToken = default) { - return new(true); + return true; } - public ValueTask> GetCredentialsAsync(CancellationToken cancellationToken = default) + public async ValueTask> GetCredentialsAsync(CancellationToken cancellationToken = default) { - return new(ImmutableDictionary.Empty); + return ImmutableDictionary.Empty; } protected virtual void OnCredentialsChanged(EventArgs args) => this.CredentialsChanged?.Invoke(this, args); diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/Services/BrokeredServiceBridgeManifest/BrokeredServiceBridgeManifestService.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/Services/BrokeredServiceBridgeManifest/BrokeredServiceBridgeManifestService.cs index 4c65e7361beab..593541ec74342 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/Services/BrokeredServiceBridgeManifest/BrokeredServiceBridgeManifestService.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/Services/BrokeredServiceBridgeManifest/BrokeredServiceBridgeManifestService.cs @@ -38,7 +38,7 @@ public BrokeredServiceBridgeManifest(ServiceBrokerFactory serviceBrokerFactory, /// /// Returns a subset of services registered to Microsoft.VisualStudio.Code.Server container that are proferred by the Language Server process. /// - public ValueTask> GetAvailableServicesAsync(CancellationToken cancellationToken) + public async ValueTask> GetAvailableServicesAsync(CancellationToken cancellationToken) { var services = (IReadOnlyCollection)[.. _serviceBrokerFactory.GetRequiredServiceBrokerContainer().GetRegisteredServices() .Select(s => s.Key) @@ -46,12 +46,11 @@ public ValueTask> GetAvailableServicesAsync( s.Name.StartsWith("Microsoft.VisualStudio.LanguageServer.", StringComparison.Ordinal) || s.Name.StartsWith("Microsoft.VisualStudio.LanguageServices.", StringComparison.Ordinal))]; _logger.LogDebug($"Proffered services: {string.Join(',', services.Select(s => s.ToString()))}"); - return ValueTask.FromResult(services); + return services; } - public Task InitializeAsync(CancellationToken cancellationToken) + public async Task InitializeAsync(CancellationToken cancellationToken) { - return Task.CompletedTask; } } #pragma warning restore RS0030 // Do not used banned APIs diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/CanonicalMiscFilesProjectLoader.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/CanonicalMiscFilesProjectLoader.cs index 1e77769b8b924..1dc74897b658f 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/CanonicalMiscFilesProjectLoader.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/CanonicalMiscFilesProjectLoader.cs @@ -276,10 +276,9 @@ private TextDocument CreatePrimordialProjectAndAddDocument_NoLock(string documen }; } - protected override ValueTask OnProjectUnloadedAsync(string projectFilePath) + protected override async ValueTask OnProjectUnloadedAsync(string projectFilePath) { // Nothing special to do on unload for canonical project - return ValueTask.CompletedTask; } protected override async ValueTask TransitionPrimordialProjectToLoaded_NoLockAsync( diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs index afa8e5e4dde15..62815a6276f4a 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs @@ -222,9 +222,8 @@ public async ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri }; } - protected override ValueTask OnProjectUnloadedAsync(string projectFilePath) + protected override async ValueTask OnProjectUnloadedAsync(string projectFilePath) { - return ValueTask.CompletedTask; } protected override async ValueTask TransitionPrimordialProjectToLoaded_NoLockAsync( diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileWatching/LspDidChangeWatchedFilesHandler.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileWatching/LspDidChangeWatchedFilesHandler.cs index 5c41b30e837d2..a7b49ced2e38b 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileWatching/LspDidChangeWatchedFilesHandler.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileWatching/LspDidChangeWatchedFilesHandler.cs @@ -23,10 +23,9 @@ public LspDidChangeWatchedFilesHandler() public bool MutatesSolutionState => false; public bool RequiresLSPSolution => false; - Task INotificationHandler.HandleNotificationAsync(DidChangeWatchedFilesParams request, RequestContext requestContext, CancellationToken cancellationToken) + async Task INotificationHandler.HandleNotificationAsync(DidChangeWatchedFilesParams request, RequestContext requestContext, CancellationToken cancellationToken) { NotificationRaised?.Invoke(this, request); - return Task.CompletedTask; } public event EventHandler? NotificationRaised; diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs index a7b83343ac0fa..9a467a701e6ae 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs @@ -102,10 +102,9 @@ public async Task OpenProjectsAsync(ImmutableArray projectFilePaths) }; } - protected override ValueTask OnProjectUnloadedAsync(string projectFilePath) + protected override async ValueTask OnProjectUnloadedAsync(string projectFilePath) { // Nothing else to unload for ordinary projects. - return ValueTask.CompletedTask; } protected override async ValueTask TransitionPrimordialProjectToLoaded_NoLockAsync( diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs index 6773f0c322a8f..1cdbc88fbdf24 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs @@ -17,13 +17,13 @@ namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.Razor; [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class RazorInitializer(Lazy workspaceFactory, [Import(AllowDefault = true)] ITelemetryReporter? telemetryReporter) : ILspService, IOnInitialized { - public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { var razorInitializerService = context.GetService(); if (razorInitializerService is null) { // No initializer service registered, nothing to do. - return Task.CompletedTask; + return; } razorInitializerService.Initialize(workspaceFactory.Value.HostWorkspace); @@ -33,7 +33,5 @@ public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestCon { razorTelemetryReporter.Initialize(new TelemetryReporterWrapper(telemetryReporter)); } - - return Task.CompletedTask; } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs index 267e4a7006e69..8e8cae416cead 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs @@ -65,10 +65,10 @@ public async Task CreateAndAddProjectAsync(WorkspaceProjectCr } } - public Task> GetSupportedBuildSystemPropertiesAsync(CancellationToken _) + public async Task> GetSupportedBuildSystemPropertiesAsync(CancellationToken _) { // TODO: implement - return Task.FromResult((IReadOnlyCollection)[]); + return []; } } #pragma warning restore RS0030 // Do not used banned APIs diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/DebugConfiguration/WorkspaceDebugConfigurationHandler.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/DebugConfiguration/WorkspaceDebugConfigurationHandler.cs index 4fe27fcea7d64..ddb95da49281b 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/DebugConfiguration/WorkspaceDebugConfigurationHandler.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/DebugConfiguration/WorkspaceDebugConfigurationHandler.cs @@ -28,7 +28,7 @@ public WorkspaceDebugConfigurationHandler(ProjectTargetFrameworkManager targetFr public bool RequiresLSPSolution => true; - public Task HandleRequestAsync(WorkspaceDebugConfigurationParams request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(WorkspaceDebugConfigurationParams request, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution, nameof(context.Solution)); @@ -36,7 +36,7 @@ public Task HandleRequestAsync(WorkspaceDebugConfig .Where(p => p.FilePath != null && p.OutputFilePath != null) .Where(p => IsProjectInWorkspace(request.WorkspacePath, p)) .Select(GetProjectDebugConfiguration).ToArray(); - return Task.FromResult(projects); + return projects; } private static bool IsProjectInWorkspace(DocumentUri workspacePath, Project project) diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Logging/UpdateLogLevelHandler.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Logging/UpdateLogLevelHandler.cs index b8651a80df060..6ad1868b95059 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Logging/UpdateLogLevelHandler.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Logging/UpdateLogLevelHandler.cs @@ -22,11 +22,10 @@ internal sealed class UpdateLogLevelHandler(ServerConfiguration serverConfigurat public bool RequiresLSPSolution => false; - public Task HandleNotificationAsync(UpdateLogLevelParams request, RequestContext requestContext, CancellationToken cancellationToken) + public async Task HandleNotificationAsync(UpdateLogLevelParams request, RequestContext requestContext, CancellationToken cancellationToken) { var level = Enum.Parse(request.LogLevelValue); serverConfiguration.LogConfiguration.UpdateLogLevel(level); - return Task.CompletedTask; } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestorableProjectsHandler.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestorableProjectsHandler.cs index dff2f53aa8ce6..f0427ed9930d6 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestorableProjectsHandler.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestorableProjectsHandler.cs @@ -25,7 +25,7 @@ internal sealed class RestorableProjectsHandler(ProjectTargetFrameworkManager pr public bool RequiresLSPSolution => true; - public Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); @@ -43,6 +43,6 @@ public Task HandleRequestAsync(RequestContext context, CancellationTok } } - return Task.FromResult(projects.ToArray()); + return projects.ToArray(); } } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.Example/ExampleRequestContextFactory.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.Example/ExampleRequestContextFactory.cs index 4b9ba38ab475f..606762c26aa8f 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.Example/ExampleRequestContextFactory.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.Example/ExampleRequestContextFactory.cs @@ -16,12 +16,12 @@ public ExampleRequestContextFactory(ILspServices lspServices) _lspServices = lspServices; } - public override Task CreateRequestContextAsync(IQueueItem queueItem, IMethodHandler methodHandler, TRequestParam requestParam, CancellationToken cancellationToken) + public override async Task CreateRequestContextAsync(IQueueItem queueItem, IMethodHandler methodHandler, TRequestParam requestParam, CancellationToken cancellationToken) { var logger = _lspServices.GetRequiredService(); var requestContext = new ExampleRequestContext(_lspServices, logger); - return Task.FromResult(requestContext); + return requestContext; } } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/Mocks/TestRequestContext.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/Mocks/TestRequestContext.cs index 2e0fbad7fa649..229fc9543cd90 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/Mocks/TestRequestContext.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/Mocks/TestRequestContext.cs @@ -13,7 +13,7 @@ internal sealed class Factory : AbstractRequestContextFactory CreateRequestContextAsync(IQueueItem queueItem, IMethodHandler methodHandler, TRequestParam requestParam, CancellationToken cancellationToken) - => Task.FromResult(new TestRequestContext()); + public override async Task CreateRequestContextAsync(IQueueItem queueItem, IMethodHandler methodHandler, TRequestParam requestParam, CancellationToken cancellationToken) + => new TestRequestContext(); } } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs index 8cb327686f775..a09f06b3dcd1c 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs @@ -60,16 +60,14 @@ public TestLifeCycleManager(TaskCompletionSource shuttingDownSource, TaskCo _exitingSource = exitingSource; } - public Task ExitAsync() + public async Task ExitAsync() { _exitingSource.SetResult(0); - return Task.CompletedTask; } - public Task ShutdownAsync(string message = "Shutting down") + public async Task ShutdownAsync(string message = "Shutting down") { _shuttingDownSource.SetResult(0); - return Task.CompletedTask; } } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializeHandler.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializeHandler.cs index 2552058e13c5b..f10cec2138dce 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializeHandler.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializeHandler.cs @@ -23,12 +23,12 @@ public InitializeHandler(IInitializeManager capabilitiesMan public bool MutatesSolutionState => true; - public Task HandleRequestAsync(TRequest request, TRequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(TRequest request, TRequestContext context, CancellationToken cancellationToken) { _capabilitiesManager.SetInitializeParams(request); var serverCapabilities = _capabilitiesManager.GetInitializeResult(); - return Task.FromResult(serverCapabilities); + return serverCapabilities; } } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializedHandler.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializedHandler.cs index 30e014534168f..2e8da373ae885 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializedHandler.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializedHandler.cs @@ -18,7 +18,7 @@ internal sealed class InitializedHandler : INotificat public bool MutatesSolutionState => true; - public Task HandleNotificationAsync(TRequest request, TRequestContext requestContext, CancellationToken cancellationToken) + public async Task HandleNotificationAsync(TRequest request, TRequestContext requestContext, CancellationToken cancellationToken) { if (HasBeenInitialized) { @@ -26,7 +26,5 @@ public Task HandleNotificationAsync(TRequest request, TRequestContext requestCon } HasBeenInitialized = true; - - return Task.CompletedTask; } } diff --git a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs index ad45e29418c17..f9167c06be2df 100644 --- a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs +++ b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs @@ -78,7 +78,7 @@ internal sealed class TestSpanMapper : ISpanMappingService /// public bool SupportsMappingImportDirectives => true; - public Task> MapSpansAsync(Document document, IEnumerable spans, CancellationToken cancellationToken) + public async Task> MapSpansAsync(Document document, IEnumerable spans, CancellationToken cancellationToken) { ImmutableArray mappedResult = default; if (document.Name == GeneratedFileName) @@ -86,7 +86,7 @@ public Task> MapSpansAsync(Document document, I mappedResult = [.. spans.Select(span => new MappedSpanResult(s_mappedFilePath, s_mappedLinePosition, new TextSpan(0, 5)))]; } - return Task.FromResult(mappedResult); + return mappedResult; } public Task> GetMappedTextChangesAsync( @@ -103,7 +103,7 @@ private protected sealed class OrderLocations : Comparer public override int Compare(LSP.Location? x, LSP.Location? y) => CompareLocations(x, y); } - protected virtual ValueTask CreateExportProviderAsync() => ValueTask.FromResult(Composition.ExportProviderFactory.CreateExportProvider()); + protected virtual async ValueTask CreateExportProviderAsync() => Composition.ExportProviderFactory.CreateExportProvider(); protected virtual TestComposition Composition => FeaturesLspComposition; private protected virtual TestAnalyzerReferenceByLanguage CreateTestAnalyzersReference() diff --git a/src/LanguageServer/Protocol.TestUtilities/Workspaces/LspTestWorkspace.cs b/src/LanguageServer/Protocol.TestUtilities/Workspaces/LspTestWorkspace.cs index 025e30f45eba0..70c54361f1883 100644 --- a/src/LanguageServer/Protocol.TestUtilities/Workspaces/LspTestWorkspace.cs +++ b/src/LanguageServer/Protocol.TestUtilities/Workspaces/LspTestWorkspace.cs @@ -36,11 +36,10 @@ internal LspTestWorkspace( bool ILspWorkspace.SupportsMutation => _supportsLspMutation; - ValueTask ILspWorkspace.UpdateTextIfPresentAsync(DocumentId documentId, SourceText sourceText, CancellationToken cancellationToken) + async ValueTask ILspWorkspace.UpdateTextIfPresentAsync(DocumentId documentId, SourceText sourceText, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_supportsLspMutation); OnDocumentTextChanged(documentId, sourceText, PreservationMode.PreserveIdentity, requireDocumentPresent: false); - return ValueTask.CompletedTask; } internal override ValueTask TryOnDocumentClosedAsync(DocumentId documentId, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs b/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs index da70d86cc57ee..f038fb3b9b395 100644 --- a/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs +++ b/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs @@ -48,14 +48,14 @@ void BuildReferenceCache() } } - public Task ResolveAsync(IAssemblyReference name) + public async Task ResolveAsync(IAssemblyReference name) { - return Task.FromResult(Resolve(name)); + return Resolve(name); } - public Task ResolveModuleAsync(MetadataFile mainModule, string moduleName) + public async Task ResolveModuleAsync(MetadataFile mainModule, string moduleName) { - return Task.FromResult(ResolveModule(mainModule, moduleName)); + return ResolveModule(mainModule, moduleName); } [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Could be non-static if instance data is accessed")] diff --git a/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_OpenDocument.cs b/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_OpenDocument.cs index db886e9f5f633..9151ccc849200 100644 --- a/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_OpenDocument.cs +++ b/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_OpenDocument.cs @@ -49,7 +49,7 @@ public override async Task> GetDiagnosticsAsync(R var activeStatementSpanProvider = spanLocator != null ? new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) => spanLocator.GetSpansAsync(compileTimeSolution, documentId, filePath, cancellationToken)) - : static (_, _, _) => ValueTask.FromResult(ImmutableArray.Empty); + : static async (_, _, _) => ImmutableArray.Empty; var rudeEditDiagnostics = await proxy.GetDocumentDiagnosticsAsync(compileTimeDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); diff --git a/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_Workspace.cs b/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_Workspace.cs index 9069b39d0e3fc..8242e49a91481 100644 --- a/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_Workspace.cs +++ b/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_Workspace.cs @@ -20,15 +20,15 @@ internal static partial class EditAndContinueDiagnosticSource private sealed class ProjectSource(Project project, ImmutableArray diagnostics) : AbstractProjectDiagnosticSource(project) { - public override Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) - => Task.FromResult(diagnostics); + public override async Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) + => diagnostics; } private sealed class ClosedDocumentSource(TextDocument document, ImmutableArray diagnostics) : AbstractWorkspaceDocumentDiagnosticSource(document) { - public override Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) - => Task.FromResult(diagnostics); + public override async Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) + => diagnostics; } public static async ValueTask> CreateWorkspaceDiagnosticSourcesAsync(Solution solution, Func isDocumentOpen, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Features/FindUsages/SimpleFindUsagesContext.cs b/src/LanguageServer/Protocol/Features/FindUsages/SimpleFindUsagesContext.cs index 1b192d32ff53a..11c1473dd6c17 100644 --- a/src/LanguageServer/Protocol/Features/FindUsages/SimpleFindUsagesContext.cs +++ b/src/LanguageServer/Protocol/Features/FindUsages/SimpleFindUsagesContext.cs @@ -28,16 +28,14 @@ internal sealed class SimpleFindUsagesContext : FindUsagesContext public string Message { get; private set; } public string SearchTitle { get; private set; } - public override ValueTask ReportNoResultsAsync(string message, CancellationToken cancellationToken) + public override async ValueTask ReportNoResultsAsync(string message, CancellationToken cancellationToken) { Message = message; - return default; } - public override ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) + public override async ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) { SearchTitle = title; - return default; } public ImmutableArray GetDefinitions() @@ -56,14 +54,12 @@ public ImmutableArray GetReferences() } } - public override ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) + public override async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (_gate) { _definitionItems.Add(definition); } - - return default; } public override async ValueTask OnReferencesFoundAsync(IAsyncEnumerable references, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Handler/AbstractRefreshQueue.cs b/src/LanguageServer/Protocol/Handler/AbstractRefreshQueue.cs index 436a66f1f83f6..be7649213ec92 100644 --- a/src/LanguageServer/Protocol/Handler/AbstractRefreshQueue.cs +++ b/src/LanguageServer/Protocol/Handler/AbstractRefreshQueue.cs @@ -50,10 +50,9 @@ public AbstractRefreshQueue( _notificationManager = notificationManager; } - public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { Initialize(clientCapabilities); - return Task.CompletedTask; } public void Initialize(ClientCapabilities clientCapabilities) @@ -104,7 +103,7 @@ protected void EnqueueRefreshNotification(DocumentUri? documentUri) } } - private ValueTask FilterLspTrackedDocumentsAsync( + private async ValueTask FilterLspTrackedDocumentsAsync( LspWorkspaceManager lspWorkspaceManager, IClientLanguageServerManager notificationManager, ImmutableSegmentedList documentUris, @@ -117,7 +116,7 @@ private ValueTask FilterLspTrackedDocumentsAsync( { try { - return notificationManager.SendRequestAsync(GetWorkspaceRefreshName(), cancellationToken); + await notificationManager.SendRequestAsync(GetWorkspaceRefreshName(), cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is ObjectDisposedException or ConnectionLostException) { @@ -128,7 +127,6 @@ private ValueTask FilterLspTrackedDocumentsAsync( } // LSP is already tracking all changed documents so we don't need to send a refresh request. - return ValueTask.CompletedTask; } public virtual void Dispose() diff --git a/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs b/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs index 43b9ed45e3b73..7e0b42b94c06b 100644 --- a/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs +++ b/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs @@ -211,7 +211,7 @@ await AddTextDocumentEditsAsync( return new LSP.WorkspaceEdit { DocumentChanges = textDocumentEdits.ToArray() }; - Task AddTextDocumentDeletionsAsync( + async Task AddTextDocumentDeletionsAsync( IEnumerable removedDocuments, Func getOldDocument) where TTextDocument : TextDocument @@ -223,8 +223,6 @@ Task AddTextDocumentDeletionsAsync( textDocumentEdits.Add(new DeleteFile { DocumentUri = oldTextDoc.GetURI() }); } - - return Task.CompletedTask; } async Task AddTextDocumentAdditionsAsync( diff --git a/src/LanguageServer/Protocol/Handler/Completion/CompletionResolveHandler.cs b/src/LanguageServer/Protocol/Handler/Completion/CompletionResolveHandler.cs index b683cde8c423a..944dc39f497eb 100644 --- a/src/LanguageServer/Protocol/Handler/Completion/CompletionResolveHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Completion/CompletionResolveHandler.cs @@ -44,7 +44,7 @@ public CompletionResolveHandler(IGlobalOptionService globalOptions) public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionItem request) => GetTextDocumentCacheEntry(request); - public Task HandleRequestAsync(LSP.CompletionItem completionItem, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(LSP.CompletionItem completionItem, RequestContext context, CancellationToken cancellationToken) { var completionListCache = context.GetRequiredLspService(); @@ -52,17 +52,17 @@ public CompletionResolveHandler(IGlobalOptionService globalOptions) { // Don't have a cache associated with this completion item, cannot resolve. context.TraceWarning("No cache entry found for the provided completion item at resolve time."); - return Task.FromResult(completionItem); + return completionItem; } var document = context.GetRequiredDocument(); var capabilityHelper = new CompletionCapabilityHelper(context.GetRequiredClientCapabilities()); - return ResolveCompletionItemAsync( - completionItem, cacheEntry.CompletionList, document, _globalOptions, capabilityHelper, cancellationToken); + return await ResolveCompletionItemAsync( + completionItem, cacheEntry.CompletionList, document, _globalOptions, capabilityHelper, cancellationToken).ConfigureAwait(false); } - public static Task ResolveCompletionItemAsync( + public static async Task ResolveCompletionItemAsync( LSP.CompletionItem completionItem, Document document, IGlobalOptionService globalOptions, @@ -73,11 +73,11 @@ public CompletionResolveHandler(IGlobalOptionService globalOptions) if (!completionListCache.TryGetCompletionListCacheEntry(completionItem, out var cacheEntry)) { // Don't have a cache associated with this completion item, cannot resolve. - return Task.FromResult(completionItem); + return completionItem; } - return ResolveCompletionItemAsync( - completionItem, cacheEntry.CompletionList, document, globalOptions, capabilityHelper, cancellationToken); + return await ResolveCompletionItemAsync( + completionItem, cacheEntry.CompletionList, document, globalOptions, capabilityHelper, cancellationToken).ConfigureAwait(false); } private static async Task ResolveCompletionItemAsync( diff --git a/src/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs b/src/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs index c6499a9cf4f6a..39ca0567950e2 100644 --- a/src/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs @@ -35,16 +35,16 @@ public AbstractGoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSour public abstract Task HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken); - protected Task GetDefinitionAsync(LSP.TextDocumentPositionParams request, bool forSymbolType, RequestContext context, CancellationToken cancellationToken) + protected async Task GetDefinitionAsync(LSP.TextDocumentPositionParams request, bool forSymbolType, RequestContext context, CancellationToken cancellationToken) { var workspace = context.Workspace; var document = context.Document; if (workspace is null || document is null) - return SpecializedTasks.Null(); + return null; var linePosition = ProtocolConversions.PositionToLinePosition(request.Position); - return GetDefinitionsAsync(_globalOptions, _metadataAsSourceFileService, workspace, document, forSymbolType, linePosition, cancellationToken); + return await GetDefinitionsAsync(_globalOptions, _metadataAsSourceFileService, workspace, document, forSymbolType, linePosition, cancellationToken).ConfigureAwait(false); } internal static async Task GetDefinitionsAsync(IGlobalOptionService globalOptions, IMetadataAsSourceFileService? metadataAsSourceFileService, Workspace workspace, Document document, bool forSymbolType, LinePosition linePosition, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs index aa35b95813701..c61ea8b330837 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs @@ -26,7 +26,7 @@ internal abstract class AbstractDocumentPullDiagnosticHandler> GetOrderedDiagnosticSourcesAsync(TDiagnosticsParams diagnosticsParams, string? requestDiagnosticCategory, RequestContext context, CancellationToken cancellationToken) + protected override async ValueTask> GetOrderedDiagnosticSourcesAsync(TDiagnosticsParams diagnosticsParams, string? requestDiagnosticCategory, RequestContext context, CancellationToken cancellationToken) { // Note: context.Document may be null in the case where the client is asking about a document that we have // since removed from the workspace. In this case, we don't really have anything to process. @@ -38,15 +38,15 @@ protected override ValueTask> GetOrderedDiagno if (identifier is null || context.TextDocument is null) { context.TraceDebug("Ignoring diagnostics request because no text document was provided"); - return new([]); + return []; } if (!context.IsTracking(identifier.DocumentUri)) { context.TraceWarning($"Ignoring diagnostics request for untracked document: {identifier.DocumentUri}"); - return new([]); + return []; } - return DiagnosticSourceManager.CreateDocumentDiagnosticSourcesAsync(context, requestDiagnosticCategory, cancellationToken); + return await DiagnosticSourceManager.CreateDocumentDiagnosticSourcesAsync(context, requestDiagnosticCategory, cancellationToken).ConfigureAwait(false); } } diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs index b1490635f95ef..5d858f2452d5d 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs @@ -92,9 +92,8 @@ protected abstract ValueTask> GetOrderedDiagno /// Used by public workspace pull diagnostics to allow it to keep the connection open until /// changes occur to avoid the client spamming the server with requests. /// - protected virtual Task WaitForChangesAsync(string? category, RequestContext context, CancellationToken cancellationToken) + protected virtual async Task WaitForChangesAsync(string? category, RequestContext context, CancellationToken cancellationToken) { - return Task.CompletedTask; } public async Task HandleRequestAsync( diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractWorkspacePullDiagnosticsHandler.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractWorkspacePullDiagnosticsHandler.cs index 2ba8cae14e540..00d487b59e98c 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractWorkspacePullDiagnosticsHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractWorkspacePullDiagnosticsHandler.cs @@ -59,17 +59,17 @@ public void Dispose() _workspaceRegistrationService.LspSolutionChanged -= OnLspSolutionChanged; } - protected override ValueTask> GetOrderedDiagnosticSourcesAsync(TDiagnosticsParams diagnosticsParams, string? requestDiagnosticCategory, RequestContext context, CancellationToken cancellationToken) + protected override async ValueTask> GetOrderedDiagnosticSourcesAsync(TDiagnosticsParams diagnosticsParams, string? requestDiagnosticCategory, RequestContext context, CancellationToken cancellationToken) { if (context.ServerKind == WellKnownLspServerKinds.RazorLspServer) { // If we're being called from razor, we do not support WorkspaceDiagnostics at all. For razor, workspace // diagnostics will be handled by razor itself, which will operate by calling into Roslyn and asking for // document-diagnostics instead. - return new([]); + return []; } - return DiagnosticSourceManager.CreateWorkspaceDiagnosticSourcesAsync(context, requestDiagnosticCategory, cancellationToken); + return await DiagnosticSourceManager.CreateWorkspaceDiagnosticSourcesAsync(context, requestDiagnosticCategory, cancellationToken).ConfigureAwait(false); } private void OnLspSolutionChanged(object? sender, WorkspaceChangeEventArgs e) diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs index e7be797f951aa..4cd7ef82b419d 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs @@ -22,9 +22,9 @@ internal abstract class AbstractDocumentSyntaxAndSemanticDiagnosticSourceProvide public bool IsEnabled(ClientCapabilities clientCapabilities) => true; - public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - return new([new DocumentDiagnosticSource(kind, context.GetRequiredDocument())]); + return [new DocumentDiagnosticSource(kind, context.GetRequiredDocument())]; } [Export(typeof(IDiagnosticSourceProvider)), Shared] diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractProjectDiagnosticSource.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractProjectDiagnosticSource.cs index fd3cd71ac1f8d..600d07c6189d1 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractProjectDiagnosticSource.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractProjectDiagnosticSource.cs @@ -59,7 +59,7 @@ public override async Task> GetDiagnosticsAsync( private sealed class CodeAnalysisDiagnosticSource(Project project, ICodeAnalysisDiagnosticAnalyzerService codeAnalysisService) : AbstractProjectDiagnosticSource(project) { - public override Task> GetDiagnosticsAsync( + public override async Task> GetDiagnosticsAsync( RequestContext context, CancellationToken cancellationToken) { @@ -69,7 +69,7 @@ public override Task> GetDiagnosticsAsync( // user. As such, it is definitely not "live" data, and it should be overridden by any subsequent fresh data // that has been produced. diagnostics = ProtocolConversions.AddBuildTagIfNotPresent(diagnostics); - return Task.FromResult(diagnostics); + return diagnostics; } } } diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractWorkspaceDocumentDiagnosticSource.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractWorkspaceDocumentDiagnosticSource.cs index ec1ac69524218..495d795dfcbac 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractWorkspaceDocumentDiagnosticSource.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractWorkspaceDocumentDiagnosticSource.cs @@ -94,7 +94,7 @@ AsyncLazy> GetLazyDiagnostics() private sealed class CodeAnalysisDiagnosticSource(TextDocument document, ICodeAnalysisDiagnosticAnalyzerService codeAnalysisService) : AbstractWorkspaceDocumentDiagnosticSource(document) { - public override Task> GetDiagnosticsAsync( + public override async Task> GetDiagnosticsAsync( RequestContext context, CancellationToken cancellationToken) { @@ -104,7 +104,7 @@ public override Task> GetDiagnosticsAsync( // user. As such, it is definitely not "live" data, and it should be overridden by any subsequent fresh data // that has been produced. diagnostics = ProtocolConversions.AddBuildTagIfNotPresent(diagnostics); - return Task.FromResult(diagnostics); + return diagnostics; } } } diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs index aac612e5d8fe8..7eeb89d32eb26 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs @@ -28,15 +28,15 @@ internal sealed class PublicDocumentNonLocalDiagnosticSourceProvider( public bool IsEnabled(ClientCapabilities clientCapabilities) => true; - public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { // Non-local document diagnostics are reported only when full solution analysis is enabled for analyzer execution. if (globalOptions.GetBackgroundAnalysisScope(context.GetRequiredDocument().Project.Language) == BackgroundAnalysisScope.FullSolution) { // NOTE: Compiler does not report any non-local diagnostics, so we only ask to run non-compiler-analyzers. - return new([new NonLocalDocumentDiagnosticSource(context.GetRequiredDocument(), AnalyzerFilter.NonCompilerAnalyzer)]); + return [new NonLocalDocumentDiagnosticSource(context.GetRequiredDocument(), AnalyzerFilter.NonCompilerAnalyzer)]; } - return new([]); + return []; } } diff --git a/src/LanguageServer/Protocol/Handler/DocumentChanges/DidChangeHandler.cs b/src/LanguageServer/Protocol/Handler/DocumentChanges/DidChangeHandler.cs index f20d2f7712411..83b5b619afe6d 100644 --- a/src/LanguageServer/Protocol/Handler/DocumentChanges/DidChangeHandler.cs +++ b/src/LanguageServer/Protocol/Handler/DocumentChanges/DidChangeHandler.cs @@ -26,7 +26,7 @@ internal class DidChangeHandler() : ILspServiceDocumentRequestHandler request.TextDocument; - public Task HandleRequestAsync(DidChangeTextDocumentParams request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(DidChangeTextDocumentParams request, RequestContext context, CancellationToken cancellationToken) { var text = context.GetTrackedDocumentInfo(request.TextDocument.DocumentUri).SourceText; @@ -34,7 +34,7 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(DidChangeTextDocumentPar context.UpdateTrackedDocument(request.TextDocument.DocumentUri, text, request.TextDocument.Version); - return SpecializedTasks.Default(); + return null; } internal static bool AreChangesInReverseOrder(TextDocumentContentChangeEvent[] contentChanges) diff --git a/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs index a7a223a8e77c4..3f3e35237d313 100644 --- a/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs @@ -23,8 +23,8 @@ internal sealed class DocumentEditAndContinueDiagnosticSourceProvider() : IDiagn public bool IsEnabled(ClientCapabilities capabilities) => true; - public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - return new([EditAndContinueDiagnosticSource.CreateOpenDocumentSource(context.GetRequiredDocument())]); + return [EditAndContinueDiagnosticSource.CreateOpenDocumentSource(context.GetRequiredDocument())]; } } diff --git a/src/LanguageServer/Protocol/Handler/EditAndContinue/RegisterSolutionSnapshotHandler.cs b/src/LanguageServer/Protocol/Handler/EditAndContinue/RegisterSolutionSnapshotHandler.cs index 1c34bd1f636f5..729d9cd707de9 100644 --- a/src/LanguageServer/Protocol/Handler/EditAndContinue/RegisterSolutionSnapshotHandler.cs +++ b/src/LanguageServer/Protocol/Handler/EditAndContinue/RegisterSolutionSnapshotHandler.cs @@ -30,10 +30,10 @@ public RegisterSolutionSnapshotHandler(ISolutionSnapshotRegistry registry) public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; - public Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); var id = _registry.RegisterSolutionSnapshot(context.Solution); - return Task.FromResult(new LspSolutionSnapshotId(id.Id)); + return new LspSolutionSnapshotId(id.Id); } } diff --git a/src/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs b/src/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs index 946363b844c3f..b6c46e6ce6b88 100644 --- a/src/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs +++ b/src/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs @@ -36,14 +36,14 @@ public FoldingRangesHandler(IGlobalOptionService globalOptions) public TextDocumentIdentifier GetTextDocumentIdentifier(FoldingRangeParams request) => request.TextDocument; - public Task HandleRequestAsync(FoldingRangeParams request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(FoldingRangeParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document is null) - return SpecializedTasks.Null(); + return null; var lineFoldingOnly = context.GetRequiredClientCapabilities().TextDocument?.FoldingRange?.LineFoldingOnly == true; - return SpecializedTasks.AsNullable(GetFoldingRangesAsync(_globalOptions, document, lineFoldingOnly, cancellationToken)); + return await SpecializedTasks.AsNullable(GetFoldingRangesAsync(_globalOptions, document, lineFoldingOnly, cancellationToken)).ConfigureAwait(false); } internal static Task GetFoldingRangesAsync( diff --git a/src/LanguageServer/Protocol/Handler/Highlights/DocumentHighlightHandler.cs b/src/LanguageServer/Protocol/Handler/Highlights/DocumentHighlightHandler.cs index ae1aabe0d4d52..e8e929fe0b4c1 100644 --- a/src/LanguageServer/Protocol/Handler/Highlights/DocumentHighlightHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Highlights/DocumentHighlightHandler.cs @@ -40,14 +40,14 @@ public DocumentHighlightsHandler(IHighlightingService highlightingService, IGlob public TextDocumentIdentifier GetTextDocumentIdentifier(TextDocumentPositionParams request) => request.TextDocument; - public Task HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) - return SpecializedTasks.Null(); + return null; var position = ProtocolConversions.PositionToLinePosition(request.Position); - return GetHighlightsAsync(_globalOptions, _highlightingService, document, position, cancellationToken); + return await GetHighlightsAsync(_globalOptions, _highlightingService, document, position, cancellationToken).ConfigureAwait(false); } internal static async Task GetHighlightsAsync(IGlobalOptionService globalOptions, IHighlightingService highlightingService, Document document, LinePosition linePosition, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Handler/OnAutoInsert/OnAutoInsertHandler.cs b/src/LanguageServer/Protocol/Handler/OnAutoInsert/OnAutoInsertHandler.cs index cd9014d3bc9af..de7eedf1ebfec 100644 --- a/src/LanguageServer/Protocol/Handler/OnAutoInsert/OnAutoInsertHandler.cs +++ b/src/LanguageServer/Protocol/Handler/OnAutoInsert/OnAutoInsertHandler.cs @@ -42,18 +42,18 @@ internal sealed class OnAutoInsertHandler( public LSP.TextDocumentIdentifier GetTextDocumentIdentifier(LSP.VSInternalDocumentOnAutoInsertParams request) => request.TextDocument; - public Task HandleRequestAsync( + public async Task HandleRequestAsync( LSP.VSInternalDocumentOnAutoInsertParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) - return SpecializedTasks.Null(); + return null; var onAutoInsertEnabled = _globalOptions.GetOption(LspOptionsStorage.LspEnableAutoInsert, document.Project.Language); if (!onAutoInsertEnabled) - return SpecializedTasks.Null(); + return null; var servicesForDocument = _braceCompletionServices.SelectAsArray(s => s.Metadata.Language == document.Project.Language, s => s.Value); var isRazorRequest = context.ServerKind == WellKnownLspServerKinds.RazorLspServer; @@ -63,7 +63,7 @@ internal sealed class OnAutoInsertHandler( // We want adjust the braces after enter for razor and non-VS clients. // We don't do this via on type formatting as it does not support snippets. var includeNewLineBraceFormatting = isRazorRequest || !supportsVSExtensions; - return GetOnAutoInsertResponseAsync(_globalOptions, servicesForDocument, document, position, request.Character, request.Options, includeNewLineBraceFormatting, cancellationToken); + return await GetOnAutoInsertResponseAsync(_globalOptions, servicesForDocument, document, position, request.Character, request.Options, includeNewLineBraceFormatting, cancellationToken).ConfigureAwait(false); } internal static async Task GetOnAutoInsertResponseAsync( diff --git a/src/LanguageServer/Protocol/Handler/ProjectContext/GetTextDocumentWithContextHandler.cs b/src/LanguageServer/Protocol/Handler/ProjectContext/GetTextDocumentWithContextHandler.cs index 62fb88c976829..a7905f5abca7c 100644 --- a/src/LanguageServer/Protocol/Handler/ProjectContext/GetTextDocumentWithContextHandler.cs +++ b/src/LanguageServer/Protocol/Handler/ProjectContext/GetTextDocumentWithContextHandler.cs @@ -26,7 +26,7 @@ internal class GetTextDocumentWithContextHandler() : ILspServiceDocumentRequestH public TextDocumentIdentifier GetTextDocumentIdentifier(VSGetProjectContextsParams request) => new() { DocumentUri = request.TextDocument.DocumentUri }; - public Task HandleRequestAsync(VSGetProjectContextsParams request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(VSGetProjectContextsParams request, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Workspace); Contract.ThrowIfNull(context.Solution); @@ -37,7 +37,7 @@ internal class GetTextDocumentWithContextHandler() : ILspServiceDocumentRequestH if (!documentIds.Any()) { - return SpecializedTasks.Null(); + return null; } var contexts = new List(); @@ -57,10 +57,10 @@ internal class GetTextDocumentWithContextHandler() : ILspServiceDocumentRequestH var openDocumentId = documentIds.First(); var currentContextDocumentId = context.Workspace.GetDocumentIdInCurrentContext(openDocumentId); - return Task.FromResult(new VSProjectContextList + return new VSProjectContextList { ProjectContexts = [.. contexts], DefaultIndex = documentIds.IndexOf(d => d == currentContextDocumentId) - }); + }; } } diff --git a/src/LanguageServer/Protocol/Handler/References/FindUsagesLSPContext.cs b/src/LanguageServer/Protocol/Handler/References/FindUsagesLSPContext.cs index 4255fdb8221e4..08861caab5e33 100644 --- a/src/LanguageServer/Protocol/Handler/References/FindUsagesLSPContext.cs +++ b/src/LanguageServer/Protocol/Handler/References/FindUsagesLSPContext.cs @@ -372,10 +372,9 @@ private static ClassifiedTextRun[] GetClassifiedTextRuns( return classifiedTextRuns.ToArray(); } - private ValueTask ReportReferencesAsync(ImmutableSegmentedList> referencesToReport, CancellationToken cancellationToken) + private async ValueTask ReportReferencesAsync(ImmutableSegmentedList> referencesToReport, CancellationToken cancellationToken) { // We can report outside of the lock here since _progress is thread-safe. _progress.Report([.. referencesToReport]); - return ValueTask.CompletedTask; } } diff --git a/src/LanguageServer/Protocol/Handler/ServerLifetime/InitializeHandler.cs b/src/LanguageServer/Protocol/Handler/ServerLifetime/InitializeHandler.cs index e09c98d46bbca..387923e812a5e 100644 --- a/src/LanguageServer/Protocol/Handler/ServerLifetime/InitializeHandler.cs +++ b/src/LanguageServer/Protocol/Handler/ServerLifetime/InitializeHandler.cs @@ -21,7 +21,7 @@ public InitializeHandler() public bool MutatesSolutionState => true; public bool RequiresLSPSolution => false; - public Task HandleRequestAsync(InitializeParams request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(InitializeParams request, RequestContext context, CancellationToken cancellationToken) { var clientCapabilitiesManager = context.GetRequiredLspService(); var clientCapabilities = clientCapabilitiesManager.TryGetClientCapabilities(); @@ -44,9 +44,9 @@ public Task HandleRequestAsync(InitializeParams request, Reque m["capabilities"] = JsonSerializer.Serialize(serverCapabilities, ProtocolConversions.LspJsonSerializerOptions); })); - return Task.FromResult(new InitializeResult + return new InitializeResult { Capabilities = serverCapabilities, - }); + }; } } diff --git a/src/LanguageServer/Protocol/Handler/ServerLifetime/LspServiceLifeCycleManager.cs b/src/LanguageServer/Protocol/Handler/ServerLifetime/LspServiceLifeCycleManager.cs index e8bec0292d0fe..0c224504a535b 100644 --- a/src/LanguageServer/Protocol/Handler/ServerLifetime/LspServiceLifeCycleManager.cs +++ b/src/LanguageServer/Protocol/Handler/ServerLifetime/LspServiceLifeCycleManager.cs @@ -68,9 +68,7 @@ public async Task ShutdownAsync(string message = "Shutting down") } } - public Task ExitAsync() + public async Task ExitAsync() { - // We don't need any custom logic to run on exit. - return Task.CompletedTask; } } diff --git a/src/LanguageServer/Protocol/Handler/SignatureHelp/SignatureHelpHandler.cs b/src/LanguageServer/Protocol/Handler/SignatureHelp/SignatureHelpHandler.cs index 21f56aebf4574..196e036f82817 100644 --- a/src/LanguageServer/Protocol/Handler/SignatureHelp/SignatureHelpHandler.cs +++ b/src/LanguageServer/Protocol/Handler/SignatureHelp/SignatureHelpHandler.cs @@ -29,15 +29,15 @@ internal sealed class SignatureHelpHandler(SignatureHelpService signatureHelpSer public LSP.TextDocumentIdentifier GetTextDocumentIdentifier(LSP.TextDocumentPositionParams request) => request.TextDocument; - public Task HandleRequestAsync(LSP.TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(LSP.TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) - return SpecializedTasks.Null(); + return null; var supportsVisualStudioExtensions = context.GetRequiredClientCapabilities().HasVisualStudioLspCapability(); var linePosition = ProtocolConversions.PositionToLinePosition(request.Position); - return GetSignatureHelpAsync(signatureHelpService, document, linePosition, supportsVisualStudioExtensions, cancellationToken); + return await GetSignatureHelpAsync(signatureHelpService, document, linePosition, supportsVisualStudioExtensions, cancellationToken).ConfigureAwait(false); } internal static async Task GetSignatureHelpAsync(SignatureHelpService signatureHelpService, Document document, LinePosition linePosition, bool supportsVisualStudioExtensions, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Handler/SourceGenerators/SourceGeneratorRefreshQueue.cs b/src/LanguageServer/Protocol/Handler/SourceGenerators/SourceGeneratorRefreshQueue.cs index 3658140436c78..cbfad43eaac30 100644 --- a/src/LanguageServer/Protocol/Handler/SourceGenerators/SourceGeneratorRefreshQueue.cs +++ b/src/LanguageServer/Protocol/Handler/SourceGenerators/SourceGeneratorRefreshQueue.cs @@ -50,17 +50,16 @@ public SourceGeneratorRefreshQueue( _disposalTokenSource.Token); } - public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { if (clientCapabilities.HasVisualStudioLspCapability()) { // VS source generated document content is not provided by LSP. - return Task.CompletedTask; + return; } // After we have initialized we can start listening for workspace changes. _lspWorkspaceRegistrationService.LspSolutionChanged += OnLspSolutionChanged; - return Task.CompletedTask; } private void OnLspSolutionChanged(object? sender, WorkspaceChangeEventArgs e) @@ -120,27 +119,25 @@ await newProject.GetDependentVersionAsync(_disposalTokenSource.Token).ConfigureA } } - private ValueTask RefreshSourceGeneratedDocumentsAsync( + private async ValueTask RefreshSourceGeneratedDocumentsAsync( CancellationToken cancellationToken) { var hasOpenSourceGeneratedDocuments = _lspWorkspaceManager.GetTrackedLspText().Keys.Any(uri => uri.ParsedUri?.Scheme == SourceGeneratedDocumentUri.Scheme); if (!hasOpenSourceGeneratedDocuments) { // There are no opened source generated documents - we don't need to bother asking the client to refresh anything. - return ValueTask.CompletedTask; + return; } try { - return _notificationManager.SendNotificationAsync(RefreshSourceGeneratedDocumentName, cancellationToken); + await _notificationManager.SendNotificationAsync(RefreshSourceGeneratedDocumentName, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is ObjectDisposedException or ConnectionLostException) { // It is entirely possible that we're shutting down and the connection is lost while we're trying to send a notification // as this runs outside of the guaranteed ordering in the queue. We can safely ignore this exception. } - - return ValueTask.CompletedTask; } public void Dispose() diff --git a/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs index 09804a1157f42..39feacef3b39a 100644 --- a/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs @@ -23,9 +23,9 @@ internal sealed class DocumentTaskDiagnosticSourceProvider([Import] IGlobalOptio public bool IsEnabled(ClientCapabilities capabilities) => capabilities.HasVisualStudioLspCapability(); - public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - return new([new TaskListDiagnosticSource(context.GetRequiredDocument(), globalOptions)]); + return [new TaskListDiagnosticSource(context.GetRequiredDocument(), globalOptions)]; } } diff --git a/src/LanguageServer/Protocol/Handler/Tasks/WorkspaceTaskDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Tasks/WorkspaceTaskDiagnosticSourceProvider.cs index 7b341125f4ec0..29bf846470714 100644 --- a/src/LanguageServer/Protocol/Handler/Tasks/WorkspaceTaskDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Tasks/WorkspaceTaskDiagnosticSourceProvider.cs @@ -25,7 +25,7 @@ internal sealed class WorkspaceTaskDiagnosticSourceProvider([Import] IGlobalOpti public bool IsEnabled(ClientCapabilities capabilities) => capabilities.HasVisualStudioLspCapability(); - public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); @@ -42,9 +42,9 @@ public ValueTask> CreateDiagnosticSourcesAsync } } - return new(result.ToImmutableAndClear()); + return result.ToImmutableAndClear(); } - return new([]); + return []; } } diff --git a/src/LanguageServer/Protocol/Handler/WorkDoneProgress/WorkDoneProgressCancelledHandler.cs b/src/LanguageServer/Protocol/Handler/WorkDoneProgress/WorkDoneProgressCancelledHandler.cs index 84fe68cc65bfe..7d2fd3cfedf0e 100644 --- a/src/LanguageServer/Protocol/Handler/WorkDoneProgress/WorkDoneProgressCancelledHandler.cs +++ b/src/LanguageServer/Protocol/Handler/WorkDoneProgress/WorkDoneProgressCancelledHandler.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. @@ -21,11 +21,10 @@ internal sealed class WorkDoneProgressCancelledHandler() : ILspServiceNotificati public bool RequiresLSPSolution => false; - public Task HandleNotificationAsync(WorkDoneProgressCancelParams request, RequestContext requestContext, CancellationToken cancellationToken) + public async Task HandleNotificationAsync(WorkDoneProgressCancelParams request, RequestContext requestContext, CancellationToken cancellationToken) { var manager = requestContext.GetRequiredLspService(); // We always create guid tokens, so use the string sumtype directly. manager.CancelWorkDoneProgress(request.Token.Second); - return Task.CompletedTask; } } diff --git a/src/LanguageServer/Protocol/RoslynLanguageServer.cs b/src/LanguageServer/Protocol/RoslynLanguageServer.cs index ca575808b15f9..f3fae36b579f5 100644 --- a/src/LanguageServer/Protocol/RoslynLanguageServer.cs +++ b/src/LanguageServer/Protocol/RoslynLanguageServer.cs @@ -157,10 +157,9 @@ void AddBaseService(BaseService baseService) } } - public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { OnInitialized(); - return Task.CompletedTask; } public override bool TryGetLanguageForRequest(string methodName, object? serializedParameters, [NotNullWhen(true)] out string? language) diff --git a/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs b/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs index e479423f1e139..5342371a4db87 100644 --- a/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs +++ b/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs @@ -30,10 +30,10 @@ internal sealed class LspMiscellaneousFilesWorkspaceProvider(ILspServices lspSer { public bool SupportsMutation => true; - public ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument document, CancellationToken cancellationToken) + public async ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument document, CancellationToken cancellationToken) { // In this case, the only documents ever created live in the Miscellaneous Files workspace (which is this object directly), so we can just compare to 'this'. - return ValueTask.FromResult(document.Project.Solution.Workspace == this); + return document.Project.Solution.Workspace == this; } /// @@ -42,8 +42,8 @@ public ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument document, /// Calls to this method and are made /// from LSP text sync request handling which do not run concurrently. /// - public ValueTask AddMiscellaneousDocumentAsync(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) - => ValueTask.FromResult(AddMiscellaneousDocument(uri, documentText, languageId, logger)); + public async ValueTask AddMiscellaneousDocumentAsync(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) + => AddMiscellaneousDocument(uri, documentText, languageId, logger); private TextDocument? AddMiscellaneousDocument(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) { @@ -83,7 +83,7 @@ public ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument document, /// Calls to this method and are made /// from LSP text sync request handling which do not run concurrently. /// - public ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri) + public async ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri) { // We'll only ever have a single document matching this URI in the misc solution. var matchingDocument = CurrentSolution.GetDocumentIds(uri).SingleOrDefault(); @@ -103,16 +103,15 @@ public ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri) var project = CurrentSolution.GetRequiredProject(matchingDocument.ProjectId); OnProjectRemoved(project.Id); - return ValueTask.FromResult(true); + return true; } - return ValueTask.FromResult(false); + return false; } - public ValueTask UpdateTextIfPresentAsync(DocumentId documentId, SourceText sourceText, CancellationToken cancellationToken) + public async ValueTask UpdateTextIfPresentAsync(DocumentId documentId, SourceText sourceText, CancellationToken cancellationToken) { this.OnDocumentTextChanged(documentId, sourceText, PreservationMode.PreserveIdentity, requireDocumentPresent: false); - return ValueTask.CompletedTask; } private sealed class StaticSourceTextContainer(SourceText text) : SourceTextContainer diff --git a/src/LanguageServer/Protocol/Workspaces/SourceTextLoader.cs b/src/LanguageServer/Protocol/Workspaces/SourceTextLoader.cs index e585ee4c76743..c0009a60454b3 100644 --- a/src/LanguageServer/Protocol/Workspaces/SourceTextLoader.cs +++ b/src/LanguageServer/Protocol/Workspaces/SourceTextLoader.cs @@ -23,6 +23,6 @@ internal override string? FilePath => _fileUri; // TODO (https://github.com/dotnet/roslyn/issues/63583): Use options.ChecksumAlgorithm - public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(TextAndVersion.Create(_sourceText, VersionStamp.Create(), _fileUri)); + public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => TextAndVersion.Create(_sourceText, VersionStamp.Create(), _fileUri); } diff --git a/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs b/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs index 6595db73e8c26..ac2e470b71ac4 100644 --- a/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs @@ -67,9 +67,9 @@ public override TextDocumentIdentifier GetTextDocumentIdentifier(ExecuteCommandP return JsonSerializer.Deserialize((JsonElement)request.Arguments!.First(), ProtocolConversions.LspJsonSerializerOptions)!; } - public override Task HandleRequestAsync(ExecuteCommandParams request, RequestContext context, CancellationToken cancellationToken) + public override async Task HandleRequestAsync(ExecuteCommandParams request, RequestContext context, CancellationToken cancellationToken) { - return Task.FromResult(true); + return true; } } } diff --git a/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs b/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs index c60c51ae06e2c..dcbd3a4e7e054 100644 --- a/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs @@ -505,15 +505,15 @@ public TestCaretOutOfScopeCompletionService(SolutionServices services) : base(se public override string Language => LanguageNames.CSharp; - internal override Task GetCompletionsAsync(Document document, + internal override async Task GetCompletionsAsync(Document document, int caretPosition, CodeAnalysis.Completion.CompletionOptions options, OptionSet passThroughOptions, CompletionTrigger trigger = default, ImmutableHashSet roles = null, - CancellationToken cancellationToken = default) => Task.FromResult(CodeAnalysis.Completion.CompletionList.Empty); + CancellationToken cancellationToken = default) => CodeAnalysis.Completion.CompletionList.Empty; - public override Task GetChangeAsync( + public override async Task GetChangeAsync( Document document, CodeAnalysis.Completion.CompletionItem item, char? commitCharacter = null, @@ -526,7 +526,7 @@ public override void M() } """); - return Task.FromResult(CompletionChange.Create(textChange, newPosition: 0)); + return CompletionChange.Create(textChange, newPosition: 0); } internal override bool ShouldTriggerCompletion(Project project, LanguageServices languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, CodeAnalysis.Completion.CompletionOptions options, OptionSet passthroughOptions, ImmutableHashSet roles = null) @@ -535,7 +535,7 @@ internal override bool ShouldTriggerCompletion(Project project, LanguageServices internal override CompletionRules GetRules(CodeAnalysis.Completion.CompletionOptions options) => CompletionRules.Default; - internal override Task GetDescriptionAsync(Document document, CodeAnalysis.Completion.CompletionItem item, CodeAnalysis.Completion.CompletionOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken = default) - => Task.FromResult(CompletionDescription.Empty); + internal override async Task GetDescriptionAsync(Document document, CodeAnalysis.Completion.CompletionItem item, CodeAnalysis.Completion.CompletionOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken = default) + => CompletionDescription.Empty; } } diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/AbstractPullDiagnosticTestsBase.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/AbstractPullDiagnosticTestsBase.cs index 3d2cbbff7391e..e3356c4ef825c 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/AbstractPullDiagnosticTestsBase.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/AbstractPullDiagnosticTestsBase.cs @@ -372,10 +372,10 @@ private sealed class MockTypescriptDiagnosticAnalyzer : DocumentDiagnosticAnalyz public override ImmutableArray SupportedDiagnostics => [Descriptor]; - public override Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) + public override async Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) { - return Task.FromResult(ImmutableArray.Create( - Diagnostic.Create(Descriptor, Location.Create(document.FilePath!, default, default)))); + return ImmutableArray.Create( + Diagnostic.Create(Descriptor, Location.Create(document.FilePath!, default, default))); } } } diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs index 548f54f2ef519..bb99dc823bda6 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs @@ -227,23 +227,23 @@ internal sealed class TestAdditionalFileDocumentSourceProvider() : IDiagnosticSo bool IDiagnosticSourceProvider.IsEnabled(LSP.ClientCapabilities clientCapabilities) => true; - ValueTask> IDiagnosticSourceProvider.CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + async ValueTask> IDiagnosticSourceProvider.CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { if (context.TextDocument is not null && context.TextDocument is not Document) { - return new([new TestAdditionalFileDocumentSource(context.TextDocument)]); + return [new TestAdditionalFileDocumentSource(context.TextDocument)]; } - return new([]); + return []; } private class TestAdditionalFileDocumentSource(TextDocument textDocument) : IDiagnosticSource { - public Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) + public async Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) { var diagnostic = Diagnostic.Create(MockAdditionalFileDiagnosticAnalyzer.Descriptor, location: Location.Create(context.TextDocument!.FilePath!, Text.TextSpan.FromBounds(0, 0), new Text.LinePositionSpan(new Text.LinePosition(0, 0), new Text.LinePosition(0, 0))), "args"); - return Task.FromResult>([DiagnosticData.Create(diagnostic, context.TextDocument.Project)]); + return [DiagnosticData.Create(diagnostic, context.TextDocument.Project)]; } public LSP.TextDocumentIdentifier? GetDocumentIdentifier() => new() diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs index ab67bd1e23670..0625038497254 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs @@ -118,12 +118,12 @@ private sealed class TestDiagnosticSource(Document document, TestDiagnosticSourc { public const string Id = "Id"; - public override Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) + public override async Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) { Interlocked.Increment(ref provider.DiagnosticsRequestedCount); - return Task.FromResult>([new DiagnosticData(Id, category: "category", context.Document!.Name, DiagnosticSeverity.Error, DiagnosticSeverity.Error, + return [new DiagnosticData(Id, category: "category", context.Document!.Name, DiagnosticSeverity.Error, DiagnosticSeverity.Error, isEnabledByDefault: true, warningLevel: 0, [], ImmutableDictionary.Empty,context.Document!.Project.Id, - new DiagnosticDataLocation(new FileLinePositionSpan(context.Document!.FilePath!, new Text.LinePosition(0, 0), new Text.LinePosition(0, 0))))]); + new DiagnosticDataLocation(new FileLinePositionSpan(context.Document!.FilePath!, new Text.LinePosition(0, 0), new Text.LinePosition(0, 0))))]; } } @@ -138,9 +138,9 @@ private sealed class TestDiagnosticSourceProvider() : IDiagnosticSourceProvider public int DiagnosticsRequestedCount = 0; - public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - return new ValueTask>([new TestDiagnosticSource(context.Document!, this)]); + return [new TestDiagnosticSource(context.Document!, this)]; } public bool IsEnabled(LSP.ClientCapabilities clientCapabilities) diff --git a/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs b/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs index edb76dd49fa16..76678098035d3 100644 --- a/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs @@ -494,11 +494,11 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(TextDocumentIdentifier r return request; } - public Task HandleRequestAsync(TextDocumentIdentifier request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(TextDocumentIdentifier request, RequestContext context, CancellationToken cancellationToken) { var trackedDocumentInfo = context.GetTrackedDocumentInfo(request.DocumentUri); - return Task.FromResult(new TestVersionResponse(trackedDocumentInfo.LspVersion)); + return new TestVersionResponse(trackedDocumentInfo.LspVersion); } } } diff --git a/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs b/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs index a117815191a4d..3ec74706852c7 100644 --- a/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs @@ -316,9 +316,9 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequestTypeOne reque return request.TextDocumentIdentifier; } - public Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) { - return Task.FromResult(this.GetType().Name); + return this.GetType().Name; } } @@ -338,9 +338,9 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequestTypeOne reque return request.TextDocumentIdentifier; } - public Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) { - return Task.FromResult(this.GetType().Name); + return this.GetType().Name; } } @@ -355,9 +355,9 @@ internal sealed class TestRequestHandlerWithNoParams() : ILspServiceRequestHandl public bool MutatesSolutionState => true; public bool RequiresLSPSolution => true; - public Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) { - return Task.FromResult(this.GetType().Name); + return this.GetType().Name; } } @@ -370,10 +370,9 @@ internal sealed class TestNotificationHandler() : ILspServiceNotificationHandler public bool MutatesSolutionState => true; public bool RequiresLSPSolution => true; - public Task HandleNotificationAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleNotificationAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) { ResultSource.SetResult(this.GetType().Name); - return Task.CompletedTask; } } @@ -400,10 +399,9 @@ internal sealed class TestNotificationWithoutParamsHandler() : ILspServiceNotifi public bool MutatesSolutionState => true; public bool RequiresLSPSolution => true; - public Task HandleNotificationAsync(RequestContext context, CancellationToken cancellationToken) + public async Task HandleNotificationAsync(RequestContext context, CancellationToken cancellationToken) { ResultSource.SetResult(this.GetType().Name); - return Task.CompletedTask; } } @@ -438,9 +436,9 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequestTypeOne reque return request.TextDocumentIdentifier; } - public Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) { - return Task.FromResult(this.GetType().Name); + return this.GetType().Name; } } @@ -462,9 +460,9 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequestTypeTwo reque return request.TextDocumentIdentifier; } - public Task HandleRequestAsync(TestRequestTypeTwo request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(TestRequestTypeTwo request, RequestContext context, CancellationToken cancellationToken) { - return Task.FromResult(this.GetType().Name); + return this.GetType().Name; } } @@ -481,9 +479,9 @@ internal sealed class TestDuplicateLanguageSpecificHandler() : ILspServiceReques public bool MutatesSolutionState => true; public bool RequiresLSPSolution => true; - public Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) { - return Task.FromResult(this.GetType().Name); + return this.GetType().Name; } } } diff --git a/src/LanguageServer/ProtocolUnitTests/Initialize/LocaleTests.cs b/src/LanguageServer/ProtocolUnitTests/Initialize/LocaleTests.cs index c96b532168aa4..f18286f314ffb 100644 --- a/src/LanguageServer/ProtocolUnitTests/Initialize/LocaleTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Initialize/LocaleTests.cs @@ -93,9 +93,9 @@ public LocaleTestHandler() public bool MutatesSolutionState => true; public bool RequiresLSPSolution => true; - public Task HandleRequestAsync(Request request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(Request request, RequestContext context, CancellationToken cancellationToken) { - return Task.FromResult(new Response(CultureInfo.CurrentUICulture.Name)); + return new Response(CultureInfo.CurrentUICulture.Name); } } diff --git a/src/LanguageServer/ProtocolUnitTests/Ordering/LongRunningNonMutatingRequestHandler.cs b/src/LanguageServer/ProtocolUnitTests/Ordering/LongRunningNonMutatingRequestHandler.cs index d5afa895b3871..2ffac1bb8b198 100644 --- a/src/LanguageServer/ProtocolUnitTests/Ordering/LongRunningNonMutatingRequestHandler.cs +++ b/src/LanguageServer/ProtocolUnitTests/Ordering/LongRunningNonMutatingRequestHandler.cs @@ -28,13 +28,13 @@ public LongRunningNonMutatingRequestHandler() public bool RequiresLSPSolution => true; - public Task HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) { do { if (cancellationToken.IsCancellationRequested) { - return Task.FromResult(new TestResponse()); + return new TestResponse(); } Thread.Sleep(100); diff --git a/src/LanguageServer/ProtocolUnitTests/Ordering/NonLSPSolutionRequestHandlerProvider.cs b/src/LanguageServer/ProtocolUnitTests/Ordering/NonLSPSolutionRequestHandlerProvider.cs index 38c122a1bdaaa..aff916af644b2 100644 --- a/src/LanguageServer/ProtocolUnitTests/Ordering/NonLSPSolutionRequestHandlerProvider.cs +++ b/src/LanguageServer/ProtocolUnitTests/Ordering/NonLSPSolutionRequestHandlerProvider.cs @@ -27,10 +27,10 @@ public NonLSPSolutionRequestHandler() public bool MutatesSolutionState => false; public bool RequiresLSPSolution => false; - public Task HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) { Assert.Null(context.Solution); - return Task.FromResult(new TestResponse()); + return new TestResponse(); } } diff --git a/src/LanguageServer/ProtocolUnitTests/Rename/WillRenameTests.cs b/src/LanguageServer/ProtocolUnitTests/Rename/WillRenameTests.cs index c6fefb8c008d7..2504b2e663ec2 100644 --- a/src/LanguageServer/ProtocolUnitTests/Rename/WillRenameTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Rename/WillRenameTests.cs @@ -152,9 +152,9 @@ private class TestWillRenameListener1() : ILspWillRenameListener { public WorkspaceEdit Result { get; set; } - public Task HandleWillRenameAsync(RenameFilesParams renameParams, RequestContext context, CancellationToken cancellationToken) + public async Task HandleWillRenameAsync(RenameFilesParams renameParams, RequestContext context, CancellationToken cancellationToken) { - return Task.FromResult(Result); + return Result; } } diff --git a/src/LanguageServer/ProtocolUnitTests/Symbols/WorkspaceSymbolsTests.cs b/src/LanguageServer/ProtocolUnitTests/Symbols/WorkspaceSymbolsTests.cs index 213721f2f4ea1..329885f80e6e4 100644 --- a/src/LanguageServer/ProtocolUnitTests/Symbols/WorkspaceSymbolsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Symbols/WorkspaceSymbolsTests.cs @@ -261,7 +261,7 @@ private static string GetContainerName(Solution solution, string? containingSymb [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] protected sealed class TestWorkspaceNavigateToSearchHostService() : IWorkspaceNavigateToSearcherHostService { - public ValueTask IsFullyLoadedAsync(CancellationToken cancellationToken) - => new(true); + public async ValueTask IsFullyLoadedAsync(CancellationToken cancellationToken) + => true; } } diff --git a/src/LanguageServer/ProtocolUnitTests/UriTests.cs b/src/LanguageServer/ProtocolUnitTests/UriTests.cs index 020f9db691c8e..9bf3c82952be9 100644 --- a/src/LanguageServer/ProtocolUnitTests/UriTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/UriTests.cs @@ -383,9 +383,9 @@ private sealed class CustomResolveHandler() : ILspServiceDocumentRequestHandler< public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public LSP.TextDocumentIdentifier GetTextDocumentIdentifier(CustomResolveParams request) => request.TextDocument; - public Task HandleRequestAsync(CustomResolveParams request, RequestContext context, CancellationToken cancellationToken) + public async Task HandleRequestAsync(CustomResolveParams request, RequestContext context, CancellationToken cancellationToken) { - return Task.FromResult(new ResolvedDocumentInfo(context.Workspace!.Kind!, context.GetRequiredDocument().Project.Language)); + return new ResolvedDocumentInfo(context.Workspace!.Kind!, context.GetRequiredDocument().Project.Language); } } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs index 25ec18d52c2e1..e0ab97d63dc41 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs @@ -45,7 +45,7 @@ public sealed partial class AnalyzerReleaseTrackingFix() : CodeFixProvider public override FixAllProvider GetFixAllProvider() => new ReleaseTrackingFixAllProvider(); - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -98,15 +98,13 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) context.RegisterCodeFix(codeAction, diagnostic); } } - - return Task.CompletedTask; } - private static Task AddAnalyzerReleaseTrackingFilesAsync(Project project) + private static async Task AddAnalyzerReleaseTrackingFilesAsync(Project project) { project = AddAdditionalDocument(project, ReleaseTrackingHelper.ShippedFileName, ShippedAnalyzerReleaseTrackingFileDefaultContent); project = AddAdditionalDocument(project, ReleaseTrackingHelper.UnshippedFileName, UnshippedAnalyzerReleaseTrackingFileDefaultContent); - return Task.FromResult(project.Solution); + return project.Solution; // Local functions. static Project AddAdditionalDocument(Project project, string name, string fileContent) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs index 1cb707aa50379..38156a2aa8967 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs @@ -59,7 +59,7 @@ private void AddFix(string codeFixTitle, CodeFixContext context, SyntaxNode root context.RegisterCodeFix(fix, context.Diagnostics); } - private Task GetFixAsync(Document document, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages) + private async Task GetFixAsync(Document document, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages) { var languageNamesFullName = typeof(LanguageNames).FullName; var arguments = new SyntaxNode[languages.Length]; @@ -75,7 +75,7 @@ private Task GetFixAsync(Document document, SyntaxNode root, SyntaxNod var attribute = generator.Attribute(WellKnownTypeNames.MicrosoftCodeAnalysisDiagnosticsDiagnosticAnalyzerAttribute, arguments); var newClassDecl = generator.AddAttributes(classDecl, attribute); var newRoot = root.ReplaceNode(classDecl, newClassDecl); - return Task.FromResult(document.WithSyntaxRoot(newRoot)); + return document.WithSyntaxRoot(newRoot); } public sealed override FixAllProvider GetFixAllProvider() diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs index 829ec829b11cf..d5634c9d5df41 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs @@ -31,7 +31,7 @@ public abstract class CompareSymbolsCorrectlyFix : CodeFixProvider public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -58,8 +58,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) } } } - - return Task.CompletedTask; } private async Task ConvertToEqualsAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs index fb253eb9fc60c..00ddf3a4d3561 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs @@ -25,7 +25,7 @@ public abstract class ConfigureGeneratedCodeAnalysisFix : CodeFixProvider public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -36,8 +36,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: nameof(ConfigureGeneratedCodeAnalysisFix)), diagnostic); } - - return Task.CompletedTask; } private async Task ConfigureGeneratedCodeAnalysisAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs index bd56a0fd5dade..4aab9a921dc48 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs @@ -24,7 +24,7 @@ public abstract class EnableConcurrentExecutionFix : CodeFixProvider public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -35,8 +35,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: nameof(EnableConcurrentExecutionFix)), diagnostic); } - - return Task.CompletedTask; } private async Task EnableConcurrentExecutionAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/PreferIsKindFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/PreferIsKindFix.cs index f9c870e37760c..5a6fd58f66573 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/PreferIsKindFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/PreferIsKindFix.cs @@ -19,7 +19,7 @@ public abstract class PreferIsKindFix : CodeFixProvider public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -30,8 +30,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: nameof(PreferIsKindFix)), diagnostic); } - - return Task.CompletedTask; } private async Task ConvertKindToIsKindAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs index 66b30fdd3cdf6..05c14b65317c6 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs @@ -32,7 +32,7 @@ public sealed class AnnotatePublicApiFix() : CodeFixProvider public sealed override FixAllProvider GetFixAllProvider() => new PublicSurfaceAreaFixAllProvider(); - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { Project project = context.Document.Project; @@ -66,7 +66,7 @@ publicSymbolNameWithNullability is null || } } - return Task.CompletedTask; + return; static async Task GetFixAsync(TextDocument publicSurfaceAreaDocument, string oldSymbolName, string newSymbolName, CancellationToken cancellationToken) { diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs index 2a9a44ebefc03..dff68fccd840a 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs @@ -33,7 +33,7 @@ public sealed override FixAllProvider GetFixAllProvider() return new PublicSurfaceAreaFixAllProvider(); } - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var project = context.Document.Project; @@ -63,8 +63,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) diagnostic); } } - - return Task.CompletedTask; } private static IEnumerable GetUnshippedPublicApiFiles(Project project, bool isPublic) diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs index 121ad21a71cd2..a709b2c043b91 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs @@ -29,7 +29,7 @@ public sealed class NullableEnablePublicApiFix() : CodeFixProvider public sealed override FixAllProvider GetFixAllProvider() => new PublicSurfaceAreaFixAllProvider(); - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { Project project = context.Document.Project; @@ -49,8 +49,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) diagnostic); } } - - return Task.CompletedTask; } private static async Task GetFixAsync(TextDocument surfaceAreaDocument, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/PreferNullLiteralCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/PreferNullLiteralCodeFixProvider.cs index a57e1c259ac68..3987368d5fd83 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/PreferNullLiteralCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/PreferNullLiteralCodeFixProvider.cs @@ -30,7 +30,7 @@ public class PreferNullLiteralCodeFixProvider() : CodeFixProvider public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -41,8 +41,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: nameof(PreferNullLiteralCodeFixProvider)), diagnostic); } - - return Task.CompletedTask; } private static async Task ReplaceWithNullLiteralAsync(Document document, Location location, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs index 3cb4590ffc788..885752b34de0a 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs @@ -21,11 +21,9 @@ public sealed override FixAllProvider GetFixAllProvider() return WellKnownFixAllProviders.BatchFixer; } - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { // Fixer not yet implemented. - return Task.CompletedTask; - } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs index b642602f35feb..c4982b7976841 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs @@ -32,7 +32,7 @@ public class ExportedPartsShouldHaveImportingConstructorCodeFixProvider() : Code public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -72,8 +72,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: scenario), diagnostic); } - - return Task.CompletedTask; } private static async Task AddExplicitImportingConstructorAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs index d4a449d92b89d..09108f1e6d9c5 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs @@ -29,7 +29,7 @@ public abstract class AbstractImportingConstructorShouldBeObsoleteCodeFixProvide public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -78,8 +78,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: scenario), diagnostic); } - - return Task.CompletedTask; } private async Task AddObsoleteAttributeAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.Fixer.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.Fixer.cs index ba2a682a7b2c2..90b84571c7af5 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.Fixer.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.Fixer.cs @@ -58,11 +58,11 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) private static bool TryGetDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration) => (declaration = node.FirstAncestorOrSelf()) is not null; - private static Task AddSharedAttributeAsync(Document document, SyntaxNode root, SyntaxNode declaration) + private static async Task AddSharedAttributeAsync(Document document, SyntaxNode root, SyntaxNode declaration) { var generator = SyntaxGenerator.GetGenerator(document); var newDeclaration = generator.AddAttributes(declaration, generator.Attribute(typeof(SharedAttribute).FullName)); - return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(declaration, newDeclaration))); + return document.WithSyntaxRoot(root.ReplaceNode(declaration, newDeclaration)); } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs index f596347c9cee0..011e07cbe1fac 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs @@ -32,7 +32,7 @@ public class TestExportsShouldNotBeDiscoverableCodeFixProvider() : CodeFixProvid public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -43,8 +43,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: nameof(TestExportsShouldNotBeDiscoverable)), diagnostic); } - - return Task.CompletedTask; } private static async Task AddPartNotDiscoverableAttributeAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Text.Analyzers/Core/IdentifiersShouldBeSpelledCorrectly.Fixer.cs b/src/RoslynAnalyzers/Text.Analyzers/Core/IdentifiersShouldBeSpelledCorrectly.Fixer.cs index 554fa6a98f8ac..55731d7985b2b 100644 --- a/src/RoslynAnalyzers/Text.Analyzers/Core/IdentifiersShouldBeSpelledCorrectly.Fixer.cs +++ b/src/RoslynAnalyzers/Text.Analyzers/Core/IdentifiersShouldBeSpelledCorrectly.Fixer.cs @@ -21,11 +21,9 @@ public sealed override FixAllProvider GetFixAllProvider() return WellKnownFixAllProviders.BatchFixer; } - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { // Fixer not yet implemented. - return Task.CompletedTask; - } } } diff --git a/src/VisualStudio/CSharp/Impl/CSharpPackage.cs b/src/VisualStudio/CSharp/Impl/CSharpPackage.cs index d085fa72391ec..c12fedcdbe6d1 100644 --- a/src/VisualStudio/CSharp/Impl/CSharpPackage.cs +++ b/src/VisualStudio/CSharp/Impl/CSharpPackage.cs @@ -67,7 +67,7 @@ protected override void RegisterInitializeAsyncWork(PackageLoadTasks packageInit packageInitializationTasks.AddTask(isMainThreadTask: false, task: PackageInitializationBackgroundThreadAsync); } - private Task PackageInitializationBackgroundThreadAsync(PackageLoadTasks packageInitializationTasks, CancellationToken cancellationToken) + private async Task PackageInitializationBackgroundThreadAsync(PackageLoadTasks packageInitializationTasks, CancellationToken cancellationToken) { try { @@ -90,8 +90,6 @@ private Task PackageInitializationBackgroundThreadAsync(PackageLoadTasks package catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, ErrorSeverity.General)) { } - - return Task.CompletedTask; } protected override void RegisterObjectBrowserLibraryManager() diff --git a/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/CodeStyle/CSharpCodeStyleSettingsProvider.cs b/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/CodeStyle/CSharpCodeStyleSettingsProvider.cs index 61559fa4ec6a4..814c27ffb1a02 100644 --- a/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/CodeStyle/CSharpCodeStyleSettingsProvider.cs +++ b/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/CodeStyle/CSharpCodeStyleSettingsProvider.cs @@ -33,7 +33,7 @@ public CSharpCodeStyleSettingsProvider( Update(); } - protected override Task UpdateOptionsAsync( + protected override async Task UpdateOptionsAsync( TieredAnalyzerConfigOptions options, ImmutableArray projectsInScope, CancellationToken cancellationToken) { var varSettings = GetVarCodeStyleOptions(options, SettingsUpdater); @@ -65,8 +65,6 @@ protected override Task UpdateOptionsAsync( var unusedValueSettings = GetUnusedValueCodeStyleOptions(options, SettingsUpdater); AddRange(unusedValueSettings); - - return Task.CompletedTask; } private static IEnumerable GetVarCodeStyleOptions(TieredAnalyzerConfigOptions options, OptionUpdater updater) diff --git a/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/Whitespace/CSharpWhitespaceSettingsProvider.cs b/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/Whitespace/CSharpWhitespaceSettingsProvider.cs index 5b1dec17cb78c..104fbf0424e1e 100644 --- a/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/Whitespace/CSharpWhitespaceSettingsProvider.cs +++ b/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/Whitespace/CSharpWhitespaceSettingsProvider.cs @@ -28,7 +28,7 @@ public CSharpWhitespaceSettingsProvider(IThreadingContext threadingContext, stri Update(); } - protected override Task UpdateOptionsAsync( + protected override async Task UpdateOptionsAsync( TieredAnalyzerConfigOptions options, ImmutableArray projectsInScope, CancellationToken cancellationToken) { var spacingOptions = GetSpacingOptions(options, SettingsUpdater); @@ -39,8 +39,6 @@ protected override Task UpdateOptionsAsync( AddRange(indentationOptions.ToImmutableArray()); var wrappingOptions = GetWrappingOptions(options, SettingsUpdater); AddRange(wrappingOptions.ToImmutableArray()); - - return Task.CompletedTask; } private static IEnumerable GetSpacingOptions(TieredAnalyzerConfigOptions options, OptionUpdater updaterService) diff --git a/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchDocumentNavigationService.cs b/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchDocumentNavigationService.cs index 44adda02940ba..bfa22be013cf0 100644 --- a/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchDocumentNavigationService.cs +++ b/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchDocumentNavigationService.cs @@ -22,14 +22,14 @@ namespace Microsoft.VisualStudio.LanguageServices.CSharp; internal sealed class SemanticSearchDocumentNavigationService(SemanticSearchToolWindowImpl window) : AbstractDocumentNavigationService { - public override Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) - => SpecializedTasks.True; + public override async Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) + => true; - public override Task GetLocationForSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) + public override async Task GetLocationForSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) { Debug.Assert(workspace is SemanticSearchWorkspace); Debug.Assert(documentId == window.SemanticSearchService.GetQueryDocumentId(workspace.CurrentSolution)); - return Task.FromResult(window.GetNavigableLocation(textSpan)); + return window.GetNavigableLocation(textSpan); } } diff --git a/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchQueryExecutor.cs b/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchQueryExecutor.cs index 3a26ad85af2c7..722533b98ac37 100644 --- a/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchQueryExecutor.cs +++ b/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchQueryExecutor.cs @@ -32,8 +32,8 @@ private sealed class ResultsObserver(IFindUsagesContext presenterContext, IOptio private readonly Lazy changes)>> _lazyDocumentUpdates = new(); private readonly Lazy> _lazyTextFileUpdates = new(); - public ValueTask GetClassificationOptionsAsync(Microsoft.CodeAnalysis.Host.LanguageServices language, CancellationToken cancellationToken) - => new(options.GetClassificationOptions(language.Language)); + public async ValueTask GetClassificationOptionsAsync(Microsoft.CodeAnalysis.Host.LanguageServices language, CancellationToken cancellationToken) + => options.GetClassificationOptions(language.Language); public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) => presenterContext.OnDefinitionFoundAsync(definition, cancellationToken); @@ -48,16 +48,14 @@ public ValueTask OnUserCodeExceptionAsync(UserCodeExceptionInfo exception, Cance => presenterContext.OnDefinitionFoundAsync( new SearchExceptionDefinitionItem(exception.Message, exception.TypeName, exception.StackTrace, (queryDocument != null) ? new DocumentSpan(queryDocument, exception.Span) : default), cancellationToken); - public ValueTask OnLogMessageAsync(string message, CancellationToken cancellationToken) + public async ValueTask OnLogMessageAsync(string message, CancellationToken cancellationToken) { logMessage(message); - return ValueTask.CompletedTask; } - public ValueTask OnDocumentUpdatedAsync(DocumentId documentId, ImmutableArray changes, CancellationToken cancellationToken) + public async ValueTask OnDocumentUpdatedAsync(DocumentId documentId, ImmutableArray changes, CancellationToken cancellationToken) { _lazyDocumentUpdates.Value.Push((documentId, changes)); - return ValueTask.CompletedTask; } private ImmutableArray<(DocumentId documentId, ImmutableArray changes)> GetDocumentUpdates() @@ -94,10 +92,9 @@ public async ValueTask GetUpdatedSolutionAsync(Solution oldSolution, C public ImmutableArray<(string filePath, string? newContent)> GetFileUpdates() => _lazyTextFileUpdates.IsValueCreated ? _lazyTextFileUpdates.Value.SelectAsArray(static entry => (entry.Key, entry.Value)) : []; - public ValueTask OnTextFileUpdatedAsync(string filePath, string? newContent, CancellationToken cancellationToken) + public async ValueTask OnTextFileUpdatedAsync(string filePath, string? newContent, CancellationToken cancellationToken) { _lazyTextFileUpdates.Value.TryAdd(filePath, newContent); - return ValueTask.CompletedTask; } } diff --git a/src/VisualStudio/CSharp/Test/EditorConfigSettings/DataProvider/DataProviderTests.MockAnalyzerReference.cs b/src/VisualStudio/CSharp/Test/EditorConfigSettings/DataProvider/DataProviderTests.MockAnalyzerReference.cs index 4053e232c7efb..106809d623bef 100644 --- a/src/VisualStudio/CSharp/Test/EditorConfigSettings/DataProvider/DataProviderTests.MockAnalyzerReference.cs +++ b/src/VisualStudio/CSharp/Test/EditorConfigSettings/DataProvider/DataProviderTests.MockAnalyzerReference.cs @@ -60,11 +60,10 @@ public sealed class MockFixer : CodeFixProvider public sealed override ImmutableArray FixableDiagnosticIds => [Id]; - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { Called = true; ContextDiagnosticsCount = context.Diagnostics.Length; - return Task.CompletedTask; } } diff --git a/src/VisualStudio/CSharp/Test/Interactive/Commands/TestResetInteractive.cs b/src/VisualStudio/CSharp/Test/Interactive/Commands/TestResetInteractive.cs index f5f66d2d47e1a..0ae05af549bb4 100644 --- a/src/VisualStudio/CSharp/Test/Interactive/Commands/TestResetInteractive.cs +++ b/src/VisualStudio/CSharp/Test/Interactive/Commands/TestResetInteractive.cs @@ -58,10 +58,10 @@ protected override void CancelBuildProject() CancelBuildProjectCount++; } - protected override Task BuildProjectAsync() + protected override async Task BuildProjectAsync() { BuildProjectCount++; - return Task.FromResult(_buildSucceeds); + return _buildSucceeds; } protected override bool GetProjectProperties( @@ -86,8 +86,8 @@ protected override IUIThreadOperationExecutor GetUIThreadOperationExecutor() return _uiThreadOperationExecutor; } - protected override Task> GetNamespacesToImportAsync(IEnumerable namespacesToImport, IInteractiveWindow interactiveWindow) + protected override async Task> GetNamespacesToImportAsync(IEnumerable namespacesToImport, IInteractiveWindow interactiveWindow) { - return Task.FromResult((IEnumerable)NamespacesToImport); + return (IEnumerable)NamespacesToImport; } } diff --git a/src/VisualStudio/CSharp/Test/Interactive/TestInteractiveEvaluator.cs b/src/VisualStudio/CSharp/Test/Interactive/TestInteractiveEvaluator.cs index 79e88ecdc01a8..6ea2d516987fc 100644 --- a/src/VisualStudio/CSharp/Test/Interactive/TestInteractiveEvaluator.cs +++ b/src/VisualStudio/CSharp/Test/Interactive/TestInteractiveEvaluator.cs @@ -23,19 +23,19 @@ public void Dispose() { } - public Task InitializeAsync() - => Task.FromResult(ExecutionResult.Success); + public async Task InitializeAsync() + => ExecutionResult.Success; - public Task ResetAsync(bool initialize = true) - => Task.FromResult(ExecutionResult.Success); + public async Task ResetAsync(bool initialize = true) + => ExecutionResult.Success; public bool CanExecuteCode(string text) => true; - public Task ExecuteCodeAsync(string text) + public async Task ExecuteCodeAsync(string text) { OnExecute?.Invoke(this, text); - return Task.FromResult(ExecutionResult.Success); + return ExecutionResult.Success; } public string FormatClipboard() diff --git a/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs b/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs index a6d07c92f40a3..ca8ec5fe83a30 100644 --- a/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs +++ b/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs @@ -62,20 +62,20 @@ public void Dispose() _cancellationTokenSource.Cancel(); } - public Task CanCreateDataPointAsync( + public async Task CanCreateDataPointAsync( CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken) { if (descriptorContext != null && descriptorContext.ApplicableSpan.HasValue) { // we allow all reference points. // engine will call this for all points our roslyn code lens (reference) tagger tagged. - return SpecializedTasks.True; + return true; } - return SpecializedTasks.False; + return false; } - public Task CreateDataPointAsync( + public async Task CreateDataPointAsync( CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken) { var dataPoint = new DataPoint( @@ -84,7 +84,7 @@ public Task CreateDataPointAsync( descriptor); AddDataPoint(dataPoint); - return Task.FromResult(dataPoint); + return dataPoint; } // The current CodeLens OOP design does not allow us to register an event handler for WorkspaceChanged events diff --git a/src/VisualStudio/Core/Def/CodeCleanup/AbstractCodeCleanUpFixer.cs b/src/VisualStudio/Core/Def/CodeCleanup/AbstractCodeCleanUpFixer.cs index 80d620c98b01b..e35b9a87b5fa8 100644 --- a/src/VisualStudio/Core/Def/CodeCleanup/AbstractCodeCleanUpFixer.cs +++ b/src/VisualStudio/Core/Def/CodeCleanup/AbstractCodeCleanUpFixer.cs @@ -136,23 +136,23 @@ private async Task FixHierarchyContentAsync(IVsHierarchyCodeCleanupScope h return false; } - private Task FixTextBufferAsync(TextBufferCodeCleanUpScope textBufferScope, ICodeCleanUpExecutionContext context) + private async Task FixTextBufferAsync(TextBufferCodeCleanUpScope textBufferScope, ICodeCleanUpExecutionContext context) { var buffer = textBufferScope.SubjectBuffer; // Let LSP handle code cleanup in the cloud scenario if (buffer.IsInLspEditorContext()) - return SpecializedTasks.False; + return false; var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) - return SpecializedTasks.False; + return false; var workspace = buffer.GetWorkspace(); if (workspace is not VisualStudioWorkspace visualStudioWorkspace) - return SpecializedTasks.False; + return false; - return FixAsync(visualStudioWorkspace, ApplyFixAsync, context); + return await FixAsync(visualStudioWorkspace, ApplyFixAsync, context).ConfigureAwait(false); // Local function async Task ApplyFixAsync(IProgress progress, CancellationToken cancellationToken) diff --git a/src/VisualStudio/Core/Def/DesignerAttribute/VisualStudioDesignerAttributeService.cs b/src/VisualStudio/Core/Def/DesignerAttribute/VisualStudioDesignerAttributeService.cs index 19186ff2d2b4e..73ba63b7daec3 100644 --- a/src/VisualStudio/Core/Def/DesignerAttribute/VisualStudioDesignerAttributeService.cs +++ b/src/VisualStudio/Core/Def/DesignerAttribute/VisualStudioDesignerAttributeService.cs @@ -311,10 +311,9 @@ private static async Task NotifyCpsProjectSystemAsync( /// /// Callback from the OOP service back into us. /// - public ValueTask ReportDesignerAttributeDataAsync(ImmutableArray data, CancellationToken cancellationToken) + public async ValueTask ReportDesignerAttributeDataAsync(ImmutableArray data, CancellationToken cancellationToken) { Contract.ThrowIfNull(_projectSystemNotificationQueue); _projectSystemNotificationQueue.AddWork(data.AsSpan()); - return ValueTask.CompletedTask; } } diff --git a/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/CodeStyle/CommonCodeStyleSettingsProvider.cs b/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/CodeStyle/CommonCodeStyleSettingsProvider.cs index 2852da33b13b2..7d21208d1d50e 100644 --- a/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/CodeStyle/CommonCodeStyleSettingsProvider.cs +++ b/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/CodeStyle/CommonCodeStyleSettingsProvider.cs @@ -29,7 +29,7 @@ public CommonCodeStyleSettingsProvider( Update(); } - protected override Task UpdateOptionsAsync( + protected override async Task UpdateOptionsAsync( TieredAnalyzerConfigOptions options, ImmutableArray projectsInScope, CancellationToken cancellationToken) { var qualifySettings = GetQualifyCodeStyleOptions(options, SettingsUpdater); @@ -60,8 +60,6 @@ protected override Task UpdateOptionsAsync( var experimentalSettings = GetExperimentalCodeStyleOptions(options, SettingsUpdater); AddRange(experimentalSettings); - - return Task.CompletedTask; } private static IEnumerable GetQualifyCodeStyleOptions(TieredAnalyzerConfigOptions options, OptionUpdater updater) diff --git a/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/Whitespace/CommonWhitespaceSettingsProvider.cs b/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/Whitespace/CommonWhitespaceSettingsProvider.cs index 24e48ecd29ad2..78c6ba5e89f40 100644 --- a/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/Whitespace/CommonWhitespaceSettingsProvider.cs +++ b/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/Whitespace/CommonWhitespaceSettingsProvider.cs @@ -29,13 +29,11 @@ public CommonWhitespaceSettingsProvider( Update(); } - protected override Task UpdateOptionsAsync( + protected override async Task UpdateOptionsAsync( TieredAnalyzerConfigOptions options, ImmutableArray projectsInScope, CancellationToken cancellationToken) { var defaultOptions = GetDefaultOptions(options, SettingsUpdater); AddRange(defaultOptions); - - return Task.CompletedTask; } private static IEnumerable GetDefaultOptions(TieredAnalyzerConfigOptions options, OptionUpdater updater) diff --git a/src/VisualStudio/Core/Def/FindReferences/Contexts/AbstractTableDataSourceFindUsagesContext.cs b/src/VisualStudio/Core/Def/FindReferences/Contexts/AbstractTableDataSourceFindUsagesContext.cs index c04271ba7a0ed..6e01e15b6e529 100644 --- a/src/VisualStudio/Core/Def/FindReferences/Contexts/AbstractTableDataSourceFindUsagesContext.cs +++ b/src/VisualStudio/Core/Def/FindReferences/Contexts/AbstractTableDataSourceFindUsagesContext.cs @@ -170,10 +170,9 @@ protected AbstractTableDataSourceFindUsagesContext( // results). To limit the amount of work we do, we'll only update the window every 250ms. _notifyQueue = new AsyncBatchingWorkQueue( DelayTimeSpan.Short, - cancellationToken => + async cancellationToken => { _tableDataSink.FactorySnapshotChanged(this); - return ValueTask.CompletedTask; }, presenter._asyncListener, CancellationTokenSource.Token); @@ -346,11 +345,10 @@ public IDisposable Subscribe(ITableDataSink sink) #region FindUsagesContext overrides. - public sealed override ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) + public sealed override async ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) { // Note: IFindAllReferenceWindow.Title is safe to set from any thread. _findReferencesWindow.Title = title; - return default; } public sealed override async ValueTask OnCompletedAsync(CancellationToken cancellationToken) @@ -528,14 +526,12 @@ protected RoslynDefinitionBucket GetOrCreateDefinitionBucket(DefinitionItem defi } } - public sealed override ValueTask ReportNoResultsAsync(string message, CancellationToken cancellationToken) + public sealed override async ValueTask ReportNoResultsAsync(string message, CancellationToken cancellationToken) { lock (Gate) { NoDefinitionsFoundMessage = message; } - - return ValueTask.CompletedTask; } public sealed override async ValueTask ReportMessageAsync(string message, NotificationSeverity severity, CancellationToken cancellationToken) @@ -543,13 +539,12 @@ public sealed override async ValueTask ReportMessageAsync(string message, Notifi await this.Presenter.ReportMessageAsync(message, severity, cancellationToken).ConfigureAwait(false); } - protected sealed override ValueTask ReportProgressAsync(int current, int maximum, CancellationToken cancellationToken) + protected sealed override async ValueTask ReportProgressAsync(int current, int maximum, CancellationToken cancellationToken) { _progressQueue.AddWork((current, maximum)); - return default; } - private ValueTask UpdateTableProgressAsync(ImmutableSegmentedList<(int current, int maximum)> nextBatch, CancellationToken _) + private async ValueTask UpdateTableProgressAsync(ImmutableSegmentedList<(int current, int maximum)> nextBatch, CancellationToken _) { if (!nextBatch.IsEmpty) { @@ -568,8 +563,6 @@ private ValueTask UpdateTableProgressAsync(ImmutableSegmentedList<(int current, if (current > 0) _findReferencesWindow.SetProgress(current, maximum); } - - return ValueTask.CompletedTask; } protected static DefinitionItem CreateNoResultsDefinitionItem(string message) diff --git a/src/VisualStudio/Core/Def/FindReferences/Entries/SimpleMessageEntry.cs b/src/VisualStudio/Core/Def/FindReferences/Entries/SimpleMessageEntry.cs index 3265dc00db67a..8454642f154fa 100644 --- a/src/VisualStudio/Core/Def/FindReferences/Entries/SimpleMessageEntry.cs +++ b/src/VisualStudio/Core/Def/FindReferences/Entries/SimpleMessageEntry.cs @@ -27,13 +27,13 @@ private SimpleMessageEntry( _message = message; } - public static Task CreateAsync( + public static async Task CreateAsync( RoslynDefinitionBucket definitionBucket, RoslynDefinitionBucket? navigationBucket, string message) { var referenceEntry = new SimpleMessageEntry(definitionBucket, navigationBucket, message); - return Task.FromResult(referenceEntry); + return referenceEntry; } protected override object? GetValueWorker(string keyName) diff --git a/src/VisualStudio/Core/Def/FindReferences/VisualStudioDefinitionsAndReferencesFactory.cs b/src/VisualStudio/Core/Def/FindReferences/VisualStudioDefinitionsAndReferencesFactory.cs index a87b2b42ce545..bfcf4b7c7458e 100644 --- a/src/VisualStudio/Core/Def/FindReferences/VisualStudioDefinitionsAndReferencesFactory.cs +++ b/src/VisualStudio/Core/Def/FindReferences/VisualStudioDefinitionsAndReferencesFactory.cs @@ -28,7 +28,7 @@ internal sealed class VisualStudioDefinitionsAndReferencesFactory( SVsServiceProvider serviceProvider, IThreadingContext threadingContext) : IExternalDefinitionItemProvider { - public async Task GetThirdPartyDefinitionItemAsync( + public async ValueTask GetThirdPartyDefinitionItemAsync( Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken) { var symbolNavigationService = solution.Services.GetRequiredService(); @@ -89,13 +89,13 @@ private sealed class ExternalDefinitionItem( { internal override bool IsExternal => true; - public override Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) + public override async Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) { - return Task.FromResult(new NavigableLocation(async (options, cancellationToken) => + return new NavigableLocation(async (options, cancellationToken) => { await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return TryOpenFile() && TryNavigateToPosition(); - })); + }); } private bool TryOpenFile() diff --git a/src/VisualStudio/Core/Def/Library/AbstractObjectList.cs b/src/VisualStudio/Core/Def/Library/AbstractObjectList.cs index 73912910b0280..c084a223528f2 100644 --- a/src/VisualStudio/Core/Def/Library/AbstractObjectList.cs +++ b/src/VisualStudio/Core/Def/Library/AbstractObjectList.cs @@ -62,8 +62,8 @@ protected virtual bool TryGetContextMenu(uint index, out Guid menuGuid, out int return false; } - protected virtual Task<(bool success, object pvar)> TryGetPropertyAsync(uint index, _VSOBJLISTELEMPROPID propertyId, CancellationToken cancellationToken) - => SpecializedTasks.Default<(bool success, object pvar)>(); + protected virtual async Task<(bool success, object pvar)> TryGetPropertyAsync(uint index, _VSOBJLISTELEMPROPID propertyId, CancellationToken cancellationToken) + => default((bool success, object pvar)); protected virtual bool TryCountSourceItems(uint index, out IVsHierarchy hierarchy, out uint itemid, out uint items) { @@ -73,16 +73,16 @@ protected virtual bool TryCountSourceItems(uint index, out IVsHierarchy hierarch return false; } - protected virtual Task GetBrowseObjectAsync(uint index, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + protected virtual async Task GetBrowseObjectAsync(uint index, CancellationToken cancellationToken) + => null; protected virtual bool SupportsNavInfo { get { return false; } } - protected virtual Task GetNavInfoAsync(uint index, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + protected virtual async Task GetNavInfoAsync(uint index, CancellationToken cancellationToken) + => null; protected virtual IVsNavInfoNode GetNavInfoNode(uint index) => null; @@ -98,8 +98,8 @@ protected virtual bool SupportsDescription get { return false; } } - protected virtual Task TryFillDescriptionAsync(uint index, _VSOBJDESCOPTIONS options, IVsObjectBrowserDescription3 description, CancellationToken cancellationToken) - => SpecializedTasks.False; + protected virtual async Task TryFillDescriptionAsync(uint index, _VSOBJDESCOPTIONS options, IVsObjectBrowserDescription3 description, CancellationToken cancellationToken) + => false; int IVsSimpleObjectList2.CanDelete(uint index, out int pfOK) { diff --git a/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultPreviewPanel.cs b/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultPreviewPanel.cs index 535834ed445cc..e83ee7bbfbd1e 100644 --- a/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultPreviewPanel.cs +++ b/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultPreviewPanel.cs @@ -34,8 +34,8 @@ public RoslynSearchResultPreviewPanel( UserInterface = new CodeEditorModel( nameof(RoslynSearchResultPreviewPanel), - new VisualStudio.Threading.AsyncLazy(() => - Task.FromResult(new TextDocumentLocation(uri, projectGuid, span)), + new VisualStudio.Threading.AsyncLazy(async () => + new TextDocumentLocation(uri, projectGuid, span), provider._threadingContext.JoinableTaskFactory), isEditable: true); } diff --git a/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultViewFactory.cs b/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultViewFactory.cs index 93cb5c7e78da9..b96e6cae4ec5b 100644 --- a/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultViewFactory.cs +++ b/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultViewFactory.cs @@ -42,8 +42,8 @@ [.. searchResult.NameMatchSpans.NullToEmpty().Select(m => m.ToSpan())]), primaryIcon: searchResult.NavigableItem.Glyph.GetImageId()); } - public Task> GetPreviewPanelsAsync(SearchResult result, SearchResultViewBase searchResultView) - => Task.FromResult(GetPreviewPanels(result, searchResultView) ?? []); + public async Task> GetPreviewPanelsAsync(SearchResult result, SearchResultViewBase searchResultView) + => GetPreviewPanels(result, searchResultView) ?? []; private IReadOnlyList? GetPreviewPanels(SearchResult result, SearchResultViewBase searchResultView) { diff --git a/src/VisualStudio/Core/Def/Options/VisualStudioOptionStorage.cs b/src/VisualStudio/Core/Def/Options/VisualStudioOptionStorage.cs index ff484050603e9..ed8884cf6391f 100644 --- a/src/VisualStudio/Core/Def/Options/VisualStudioOptionStorage.cs +++ b/src/VisualStudio/Core/Def/Options/VisualStudioOptionStorage.cs @@ -107,10 +107,9 @@ public FeatureFlagStorage(string flagName) FlagName = flagName; } - public Task PersistAsync(FeatureFlagPersister persister, object? value) + public async Task PersistAsync(FeatureFlagPersister persister, object? value) { persister.Persist(FlagName, value); - return Task.CompletedTask; } public bool TryFetch(FeatureFlagPersister persister, OptionKey2 optionKey, out object? value) @@ -122,10 +121,9 @@ internal sealed class LocalUserProfileStorage(string path, string key) : VisualS public string Path => path; public string Key => key; - public Task PersistAsync(LocalUserRegistryOptionPersister persister, OptionKey2 optionKey, object? value) + public async Task PersistAsync(LocalUserRegistryOptionPersister persister, OptionKey2 optionKey, object? value) { persister.Persist(optionKey, path, key, value); - return Task.CompletedTask; } public bool TryFetch(LocalUserRegistryOptionPersister persister, OptionKey2 optionKey, out object? value) diff --git a/src/VisualStudio/Core/Def/Options/VisualStudioSettingsOptionPersister.cs b/src/VisualStudio/Core/Def/Options/VisualStudioSettingsOptionPersister.cs index 80621591e11b1..5fedc87541e58 100644 --- a/src/VisualStudio/Core/Def/Options/VisualStudioSettingsOptionPersister.cs +++ b/src/VisualStudio/Core/Def/Options/VisualStudioSettingsOptionPersister.cs @@ -40,12 +40,11 @@ public VisualStudioSettingsOptionPersister( settingsSubset.SettingChangedAsync += OnSettingChangedAsync; } - private Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) + private async Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) { Contract.ThrowIfNull(this.SettingsManager); RefreshIfTracked(args.PropertyName); - return Task.CompletedTask; } public override bool TryFetch(OptionKey2 optionKey, string storageKey, out object? value) diff --git a/src/VisualStudio/Core/Def/Options/VisualStudioUnifiedSettingsOptionPersister.cs b/src/VisualStudio/Core/Def/Options/VisualStudioUnifiedSettingsOptionPersister.cs index 78ee53c51950a..ccb8b50bdd35f 100644 --- a/src/VisualStudio/Core/Def/Options/VisualStudioUnifiedSettingsOptionPersister.cs +++ b/src/VisualStudio/Core/Def/Options/VisualStudioUnifiedSettingsOptionPersister.cs @@ -50,7 +50,7 @@ private static void CheckStorageKeyAndType(string storageKey, [NotNull] Type? st optionKey.Option.Definition.Serializer.TryParse(stringValue, out var value) ? new(value) : default; } - public override Task PersistAsync(OptionKey2 optionKey, string storageKey, object? value) + public override async Task PersistAsync(OptionKey2 optionKey, string storageKey, object? value) { var storageType = value?.GetType(); CheckStorageKeyAndType(storageKey, storageType); @@ -65,7 +65,5 @@ public override Task PersistAsync(OptionKey2 optionKey, string storageKey, objec // ignoreCase: true, out result)` writer.EnqueueChange(storageKey, optionKey.Option.Definition.Serializer.Serialize(value).ToLowerInvariant()); writer.RequestCommit(nameof(VisualStudioUnifiedSettingsOptionPersister)); - - return Task.CompletedTask; } } diff --git a/src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs b/src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs index de3f3b67b6b30..edb29c3e9778e 100644 --- a/src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs +++ b/src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs @@ -453,7 +453,7 @@ private void OnWorkspaceChanged(WorkspaceChangeEventArgs e) _workQueue.AddWork((solutionChanged, changedProject)); } - private ValueTask ProcessWorkQueueAsync( + private async ValueTask ProcessWorkQueueAsync( ImmutableSegmentedList<(bool solutionChanged, ProjectId? changedProject)> workQueue, CancellationToken cancellationToken) { // ThisCanBeCalledOnAnyThread(); @@ -462,9 +462,9 @@ private ValueTask ProcessWorkQueueAsync( // If we've been disconnected, then there's no point proceeding. if (Workspace == null || !IsEnabled) - return ValueTask.CompletedTask; + return; - return ProcessWorkQueueWorkerAsync(workQueue, cancellationToken); + await ProcessWorkQueueWorkerAsync(workQueue, cancellationToken).ConfigureAwait(false); } [MethodImpl(MethodImplOptions.NoInlining)] diff --git a/src/VisualStudio/Core/Def/Preview/PreviewUpdater.PreviewDialogWorkspace.cs b/src/VisualStudio/Core/Def/Preview/PreviewUpdater.PreviewDialogWorkspace.cs index 52c0c30ceae6b..59f68767ae082 100644 --- a/src/VisualStudio/Core/Def/Preview/PreviewUpdater.PreviewDialogWorkspace.cs +++ b/src/VisualStudio/Core/Def/Preview/PreviewUpdater.PreviewDialogWorkspace.cs @@ -47,8 +47,8 @@ private sealed class PreviewTextLoader : TextLoader internal PreviewTextLoader(SourceText documentText) => _text = documentText; - public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(LoadTextAndVersionSynchronously(options, cancellationToken)); + public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => LoadTextAndVersionSynchronously(options, cancellationToken); internal override TextAndVersion LoadTextAndVersionSynchronously(LoadTextOptions options, CancellationToken cancellationToken) => TextAndVersion.Create(_text, VersionStamp.Create()); diff --git a/src/VisualStudio/Core/Def/Progression/GraphNodeCreation.cs b/src/VisualStudio/Core/Def/Progression/GraphNodeCreation.cs index 60076ab449d24..792d49bff8b0d 100644 --- a/src/VisualStudio/Core/Def/Progression/GraphNodeCreation.cs +++ b/src/VisualStudio/Core/Def/Progression/GraphNodeCreation.cs @@ -14,10 +14,10 @@ namespace Microsoft.VisualStudio.LanguageServices.Progression; public static class GraphNodeCreation { [Obsolete("This method is not implemented and always returns an empty GraphNodeId.", error: true)] - public static Task CreateNodeIdAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken) - => Task.FromResult(GraphNodeId.Empty); + public static async Task CreateNodeIdAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken) + => GraphNodeId.Empty; [Obsolete("This method is not implemented and always returns an empty GraphNode.", error: true)] - public static Task CreateNodeAsync(this Graph graph, ISymbol symbol, Solution solution, CancellationToken cancellationToken) - => Task.FromResult(graph.Nodes.GetOrCreate(GraphNodeId.Empty)); + public static async Task CreateNodeAsync(this Graph graph, ISymbol symbol, Solution solution, CancellationToken cancellationToken) + => graph.Nodes.GetOrCreate(GraphNodeId.Empty); } diff --git a/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProject.cs b/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProject.cs index c87c7e3861576..aa7379ad6001f 100644 --- a/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProject.cs +++ b/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProject.cs @@ -163,22 +163,19 @@ public async Task SetBuildSystemPropertiesAsync(IReadOnlyDictionary arguments, CancellationToken cancellationToken) + public async Task SetCommandLineArgumentsAsync(IReadOnlyList arguments, CancellationToken cancellationToken) { _project.SetOptions([.. arguments]); - return Task.CompletedTask; } - public Task SetDisplayNameAsync(string displayName, CancellationToken cancellationToken) + public async Task SetDisplayNameAsync(string displayName, CancellationToken cancellationToken) { _project.DisplayName = displayName; - return Task.CompletedTask; } - public Task SetProjectHasAllInformationAsync(bool hasAllInformation, CancellationToken cancellationToken) + public async Task SetProjectHasAllInformationAsync(bool hasAllInformation, CancellationToken cancellationToken) { _project.LastDesignTimeBuildSucceeded = hasAllInformation; - return Task.CompletedTask; } public async Task StartBatchAsync(CancellationToken cancellationToken) diff --git a/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProjectFactoryService.cs b/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProjectFactoryService.cs index 57744b19a71e8..c3058230d6a86 100644 --- a/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProjectFactoryService.cs +++ b/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProjectFactoryService.cs @@ -34,9 +34,9 @@ public async Task CreateAndAddProjectAsync(WorkspaceProjectCr return new WorkspaceProject(project); } - public Task> GetSupportedBuildSystemPropertiesAsync(CancellationToken cancellationToken) + public async Task> GetSupportedBuildSystemPropertiesAsync(CancellationToken cancellationToken) { - return Task.FromResult((IReadOnlyCollection)_workspaceProjectContextFactory.EvaluationItemNames); + return (IReadOnlyCollection)_workspaceProjectContextFactory.EvaluationItemNames; } private sealed class EvaluationDataShim : EvaluationData diff --git a/src/VisualStudio/Core/Def/ProjectSystem/Legacy/SolutionEventsBatchScopeCreator.cs b/src/VisualStudio/Core/Def/ProjectSystem/Legacy/SolutionEventsBatchScopeCreator.cs index 0816942fef4c1..60f09078ded3a 100644 --- a/src/VisualStudio/Core/Def/ProjectSystem/Legacy/SolutionEventsBatchScopeCreator.cs +++ b/src/VisualStudio/Core/Def/ProjectSystem/Legacy/SolutionEventsBatchScopeCreator.cs @@ -205,24 +205,20 @@ public void OnUnhandledException(Exception exception) { } - public ValueTask OnBeforeOpenSolutionAsync(BeforeOpenSolutionArgs args, CancellationToken cancellationToken) + public async ValueTask OnBeforeOpenSolutionAsync(BeforeOpenSolutionArgs args, CancellationToken cancellationToken) { - return ValueTask.CompletedTask; } - public ValueTask OnBeforeCloseSolutionAsync(BeforeCloseSolutionArgs args, CancellationToken cancellationToken) + public async ValueTask OnBeforeCloseSolutionAsync(BeforeCloseSolutionArgs args, CancellationToken cancellationToken) { - return ValueTask.CompletedTask; } - public ValueTask OnAfterCloseSolutionAsync(AfterCloseSolutionArgs args, CancellationToken cancellationToken) + public async ValueTask OnAfterCloseSolutionAsync(AfterCloseSolutionArgs args, CancellationToken cancellationToken) { - return ValueTask.CompletedTask; } - public ValueTask OnAfterRenameSolutionAsync(AfterRenameSolutionArgs args, CancellationToken cancellationToken) + public async ValueTask OnAfterRenameSolutionAsync(AfterRenameSolutionArgs args, CancellationToken cancellationToken) { - return ValueTask.CompletedTask; } #endregion diff --git a/src/VisualStudio/Core/Def/Remote/DefaultRemoteHostClientProvider.cs b/src/VisualStudio/Core/Def/Remote/DefaultRemoteHostClientProvider.cs index 7635e1501ad77..2b7535c58d492 100644 --- a/src/VisualStudio/Core/Def/Remote/DefaultRemoteHostClientProvider.cs +++ b/src/VisualStudio/Core/Def/Remote/DefaultRemoteHostClientProvider.cs @@ -14,8 +14,8 @@ namespace Microsoft.VisualStudio.LanguageServices.Remote; [method: Obsolete(MefConstruction.FactoryMethodMessage, error: true)] internal sealed class DefaultRemoteHostClientProvider() : IRemoteHostClientProvider { - public Task TryGetRemoteHostClientAsync(CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task TryGetRemoteHostClientAsync(CancellationToken cancellationToken) + => null; public Task WaitForClientCreationAsync(CancellationToken cancellationToken) => Task.CompletedTask; diff --git a/src/VisualStudio/Core/Def/Remote/VisualStudioRemoteHostClientProvider.cs b/src/VisualStudio/Core/Def/Remote/VisualStudioRemoteHostClientProvider.cs index 0eddc78a8298e..4cea589e1061d 100644 --- a/src/VisualStudio/Core/Def/Remote/VisualStudioRemoteHostClientProvider.cs +++ b/src/VisualStudio/Core/Def/Remote/VisualStudioRemoteHostClientProvider.cs @@ -139,7 +139,7 @@ private VisualStudioRemoteHostClientProvider( var client = await ServiceHubRemoteHostClient.CreateAsync(Services, configuration, localSettingsDirectory, _listenerProvider, serviceBroker, _callbackDispatchers, _threadingContext.DisposalToken).ConfigureAwait(false); // proffer in-proc brokered services: - _ = brokeredServiceContainer.Proffer(SolutionAssetProvider.ServiceDescriptor, (_, _, _, _) => ValueTask.FromResult(new SolutionAssetProvider(Services))); + _ = brokeredServiceContainer.Proffer(SolutionAssetProvider.ServiceDescriptor, async (_, _, _, _) => new SolutionAssetProvider(Services)); return client; } diff --git a/src/VisualStudio/Core/Def/RoslynPackage.cs b/src/VisualStudio/Core/Def/RoslynPackage.cs index 8c26bfde24b1b..66bc4d81a3dc5 100644 --- a/src/VisualStudio/Core/Def/RoslynPackage.cs +++ b/src/VisualStudio/Core/Def/RoslynPackage.cs @@ -86,12 +86,10 @@ protected override void RegisterOnAfterPackageLoadedAsyncWork(PackageLoadTasks a return; - Task OnAfterPackageLoadedMainThreadAsync(PackageLoadTasks afterPackageLoadedTasks, CancellationToken cancellationToken) + async Task OnAfterPackageLoadedMainThreadAsync(PackageLoadTasks afterPackageLoadedTasks, CancellationToken cancellationToken) { // load some services that have to be loaded in UI thread LoadComponentsInUIContextOnceSolutionFullyLoadedAsync(cancellationToken).Forget(); - - return Task.CompletedTask; } } @@ -102,12 +100,12 @@ private async Task ProfferServiceBrokerServicesAsync(CancellationToken cancellat serviceBrokerContainer.Proffer( WorkspaceProjectFactoryServiceDescriptor.ServiceDescriptor, - (_, _, _, _) => ValueTask.FromResult(new WorkspaceProjectFactoryService(this.ComponentModel.GetService()))); + async (_, _, _, _) => new WorkspaceProjectFactoryService(this.ComponentModel.GetService())); // Must be profferred before any C#/VB projects are loaded and the corresponding UI context activated. serviceBrokerContainer.Proffer( ManagedHotReloadLanguageServiceDescriptor.Descriptor, - (_, _, _, _) => ValueTask.FromResult(new ManagedEditAndContinueLanguageServiceBridge(this.ComponentModel.GetService()))); + async (_, _, _, _) => new ManagedEditAndContinueLanguageServiceBridge(this.ComponentModel.GetService())); } protected override async Task LoadComponentsAsync(CancellationToken cancellationToken) @@ -148,8 +146,8 @@ public override IVsAsyncToolWindowFactory GetAsyncToolWindowFactory(Guid toolWin protected override string GetToolWindowTitle(Type toolWindowType, int id) => base.GetToolWindowTitle(toolWindowType, id); - protected override Task InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) - => Task.FromResult((object?)null); + protected override async Task InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) + => (object?)null; private async Task LoadComponentsBackgroundAsync(CancellationToken cancellationToken) { diff --git a/src/VisualStudio/Core/Def/Snippets/SnippetFunctions/AbstractSnippetFunction.cs b/src/VisualStudio/Core/Def/Snippets/SnippetFunctions/AbstractSnippetFunction.cs index 2a23e190ab946..46cb0b4f3f452 100644 --- a/src/VisualStudio/Core/Def/Snippets/SnippetFunctions/AbstractSnippetFunction.cs +++ b/src/VisualStudio/Core/Def/Snippets/SnippetFunctions/AbstractSnippetFunction.cs @@ -35,9 +35,9 @@ private int GetDefaultValue(CancellationToken cancellationToken, out string valu return exitCode; } - protected virtual Task<(int ExitCode, string Value, int HasDefaultValue)> GetDefaultValueAsync(CancellationToken cancellationToken) + protected virtual async Task<(int ExitCode, string Value, int HasDefaultValue)> GetDefaultValueAsync(CancellationToken cancellationToken) { - return Task.FromResult((ExitCode: VSConstants.S_OK, Value: string.Empty, HasDefaultValue: 0)); + return (ExitCode: VSConstants.S_OK, Value: string.Empty, HasDefaultValue: 0); } private int GetCurrentValue(CancellationToken cancellationToken, out string value, out int hasCurrentValue) @@ -46,9 +46,9 @@ private int GetCurrentValue(CancellationToken cancellationToken, out string valu return exitCode; } - protected virtual Task<(int ExitCode, string Value, int HasCurrentValue)> GetCurrentValueAsync(CancellationToken cancellationToken) + protected virtual async Task<(int ExitCode, string Value, int HasCurrentValue)> GetCurrentValueAsync(CancellationToken cancellationToken) { - return Task.FromResult((ExitCode: VSConstants.S_OK, Value: string.Empty, HasDefaultValue: 0)); + return (ExitCode: VSConstants.S_OK, Value: string.Empty, HasCurrentValue: 0); } protected virtual int FieldChanged(string field, out int requeryFunction) diff --git a/src/VisualStudio/Core/Def/Telemetry/FileLogger.cs b/src/VisualStudio/Core/Def/Telemetry/FileLogger.cs index 8be4ed4130e4d..9fca096e7f9eb 100644 --- a/src/VisualStudio/Core/Def/Telemetry/FileLogger.cs +++ b/src/VisualStudio/Core/Def/Telemetry/FileLogger.cs @@ -93,7 +93,7 @@ public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int unique private void LogBlockEvent(FunctionId functionId, LogMessage logMessage, int uniquePairId, string blockEvent) => Log(functionId, $"[{blockEvent} - {uniquePairId}] {logMessage.GetMessage()}"); - private ValueTask ProcessWorkQueueAsync( + private async ValueTask ProcessWorkQueueAsync( ImmutableSegmentedList<(FunctionId functionId, string message)> list, CancellationToken cancellationToken) { using var _ = PooledStringBuilder.GetInstance(out var buffer); @@ -109,7 +109,5 @@ private ValueTask ProcessWorkQueueAsync( File.AppendAllText(_logFilePath, buffer.ToString()); }); - - return ValueTask.CompletedTask; } } diff --git a/src/VisualStudio/Core/Def/Utilities/VisualStudioNavigateToLinkService.cs b/src/VisualStudio/Core/Def/Utilities/VisualStudioNavigateToLinkService.cs index d3f2763c361c1..6f7ace14ca6f1 100644 --- a/src/VisualStudio/Core/Def/Utilities/VisualStudioNavigateToLinkService.cs +++ b/src/VisualStudio/Core/Def/Utilities/VisualStudioNavigateToLinkService.cs @@ -13,30 +13,25 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; -[ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Host)] -[Shared] -internal sealed class VisualStudioNavigateToLinkService : INavigateToLinkService +[ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Host), Shared] +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed class VisualStudioNavigateToLinkService() : INavigateToLinkService { - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public VisualStudioNavigateToLinkService() - { - } - - public Task TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) + public async Task TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) { if (!uri.IsAbsoluteUri) { - return SpecializedTasks.False; + return false; } if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) { - return SpecializedTasks.False; + return false; } StartBrowser(uri); - return SpecializedTasks.True; + return true; } public static void StartBrowser(string uri) diff --git a/src/VisualStudio/Core/Def/Workspace/VisualStudioDocumentNavigationService.cs b/src/VisualStudio/Core/Def/Workspace/VisualStudioDocumentNavigationService.cs index 016b4abbb7254..5cf6d459f1bef 100644 --- a/src/VisualStudio/Core/Def/Workspace/VisualStudioDocumentNavigationService.cs +++ b/src/VisualStudio/Core/Def/Workspace/VisualStudioDocumentNavigationService.cs @@ -104,7 +104,7 @@ public async Task CanNavigateToPositionAsync( return await GetNavigableLocationAsync(workspace, documentId, - _ => Task.FromResult(textSpan), + async _ => textSpan, text => GetVsTextSpan(text, textSpan, allowInvalidSpan), (text, span) => GetVsTextSpan(text, span, allowInvalidSpan), cancellationToken).ConfigureAwait(false); diff --git a/src/VisualStudio/Core/Impl/SolutionExplorer/Search/RoslynSolutionExplorerSearchProvider.cs b/src/VisualStudio/Core/Impl/SolutionExplorer/Search/RoslynSolutionExplorerSearchProvider.cs index a8f92c1f8fcba..a8b3732cb9817 100644 --- a/src/VisualStudio/Core/Impl/SolutionExplorer/Search/RoslynSolutionExplorerSearchProvider.cs +++ b/src/VisualStudio/Core/Impl/SolutionExplorer/Search/RoslynSolutionExplorerSearchProvider.cs @@ -80,7 +80,7 @@ public void Done(bool isFullyLoaded) { } public void ReportIncomplete() { } public void ReportProgress(int current, int maximum) { } - public Task AddResultsAsync( + public async Task AddResultsAsync( ImmutableArray results, Document? activeDocument, CancellationToken cancellationToken) @@ -92,8 +92,6 @@ public Task AddResultsAsync( var imageMoniker = result.NavigableItem.Glyph.GetImageMoniker(); resultAccumulator(new SolutionExplorerSearchResult(provider, result, name, imageMoniker)); } - - return Task.CompletedTask; } } diff --git a/src/VisualStudio/Core/Test.Next/Options/VisualStudioSettingsOptionPersisterTests.cs b/src/VisualStudio/Core/Test.Next/Options/VisualStudioSettingsOptionPersisterTests.cs index a8297d3514aa7..11a57f570272d 100644 --- a/src/VisualStudio/Core/Test.Next/Options/VisualStudioSettingsOptionPersisterTests.cs +++ b/src/VisualStudio/Core/Test.Next/Options/VisualStudioSettingsOptionPersisterTests.cs @@ -48,10 +48,9 @@ public GetValueResult TryGetValue(string name, out T value) return result; } - public Task SetValueAsync(string name, object? value, bool isMachineLocal) + public async Task SetValueAsync(string name, object? value, bool isMachineLocal) { SetValueImpl?.Invoke(name, value); - return Task.CompletedTask; } public ISettingsList GetOrCreateList(string name, bool isMachineLocal) diff --git a/src/VisualStudio/Core/Test.Next/Services/AssetProviderTests.cs b/src/VisualStudio/Core/Test.Next/Services/AssetProviderTests.cs index 2cd8b39d186c6..dad61ba775c3e 100644 --- a/src/VisualStudio/Core/Test.Next/Services/AssetProviderTests.cs +++ b/src/VisualStudio/Core/Test.Next/Services/AssetProviderTests.cs @@ -187,7 +187,7 @@ private sealed class OrderedAssetSource( ISerializerService serializerService, IReadOnlyDictionary map) : IAssetSource { - public ValueTask GetAssetsAsync( + public async ValueTask GetAssetsAsync( Checksum solutionChecksum, AssetPath assetPath, ReadOnlyMemory checksums, @@ -213,8 +213,6 @@ public ValueTask GetAssetsAsync( callback(checksum, (T)deserialized, arg); } } - - return ValueTask.CompletedTask; } } } diff --git a/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs b/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs index 65dd675cd3f83..c97ca0f6a6bea 100644 --- a/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs +++ b/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs @@ -224,10 +224,9 @@ private sealed class DesignerAttributeComputerCallback : IDesignerAttributeDisco public Task> Infos => _infosSource.Task; - public ValueTask ReportDesignerAttributeDataAsync(ImmutableArray infos, CancellationToken cancellationToken) + public async ValueTask ReportDesignerAttributeDataAsync(ImmutableArray infos, CancellationToken cancellationToken) { _infosSource.SetResult(infos); - return ValueTask.CompletedTask; } } diff --git a/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests_ExtensionMessageHandler.cs b/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests_ExtensionMessageHandler.cs index 2e8e396f7225a..670dfe8ef80bb 100644 --- a/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests_ExtensionMessageHandler.cs +++ b/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests_ExtensionMessageHandler.cs @@ -787,8 +787,8 @@ private sealed class TestHandler( string name, Func? executeCallback = null) : IExtensionMessageHandlerWrapper { - public Task ExecuteAsync(object? message, TArgument argument, CancellationToken cancellationToken) - => Task.FromResult(executeCallback!(message, argument, cancellationToken)); + public async Task ExecuteAsync(object? message, TArgument argument, CancellationToken cancellationToken) + => executeCallback!(message, argument, cancellationToken); public Type MessageType => typeof(int); diff --git a/src/VisualStudio/ExternalAccess/FSharp/Internal/Classification/FSharpClassificationService.cs b/src/VisualStudio/ExternalAccess/FSharp/Internal/Classification/FSharpClassificationService.cs index d7cf5e8a4d05a..49a43ea764e3b 100644 --- a/src/VisualStudio/ExternalAccess/FSharp/Internal/Classification/FSharpClassificationService.cs +++ b/src/VisualStudio/ExternalAccess/FSharp/Internal/Classification/FSharpClassificationService.cs @@ -81,8 +81,7 @@ public void AddSyntacticClassifications(SolutionServices services, SyntaxNode? r return new(); } - public Task AddEmbeddedLanguageClassificationsAsync(Document document, ImmutableArray textSpans, ClassificationOptions options, SegmentedList result, CancellationToken cancellationToken) + public async Task AddEmbeddedLanguageClassificationsAsync(Document document, ImmutableArray textSpans, ClassificationOptions options, SegmentedList result, CancellationToken cancellationToken) { - return Task.CompletedTask; } } diff --git a/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpEditorInlineRenameService.cs b/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpEditorInlineRenameService.cs index 7af59bf296a18..637d8582f4b42 100644 --- a/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpEditorInlineRenameService.cs +++ b/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpEditorInlineRenameService.cs @@ -202,9 +202,9 @@ public FSharpEditorInlineRenameService( public bool IsEnabled => true; - public Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) + public async Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) { - return Task.FromResult(ImmutableDictionary>.Empty); + return ImmutableDictionary>.Empty; } public async Task GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) diff --git a/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FindUsages/FSharpFindUsagesContext.cs b/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FindUsages/FSharpFindUsagesContext.cs index caa330436d993..431ca25879a71 100644 --- a/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FindUsages/FSharpFindUsagesContext.cs +++ b/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FindUsages/FSharpFindUsagesContext.cs @@ -37,9 +37,8 @@ public Task ReportMessageAsync(string message) return _context.ReportNoResultsAsync(message, CancellationToken).AsTask(); } - public Task ReportProgressAsync(int current, int maximum) + public async Task ReportProgressAsync(int current, int maximum) { - return Task.CompletedTask; } public Task SetSearchTitleAsync(string title) diff --git a/src/VisualStudio/LiveShare/Impl/Client/Projects/WorkspaceFileTextLoaderNoException.cs b/src/VisualStudio/LiveShare/Impl/Client/Projects/WorkspaceFileTextLoaderNoException.cs index 2474517cbcb80..f2ad0c2ed6c58 100644 --- a/src/VisualStudio/LiveShare/Impl/Client/Projects/WorkspaceFileTextLoaderNoException.cs +++ b/src/VisualStudio/LiveShare/Impl/Client/Projects/WorkspaceFileTextLoaderNoException.cs @@ -25,13 +25,13 @@ public WorkspaceFileTextLoaderNoException(SolutionServices services, string path { } - public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) { if (!File.Exists(Path)) { - return Task.FromResult(TextAndVersion.Create(SourceText.From("", encoding: null, options.ChecksumAlgorithm), VersionStamp.Create())); + return TextAndVersion.Create(SourceText.From("", encoding: null, options.ChecksumAlgorithm), VersionStamp.Create()); } - return base.LoadTextAndVersionAsync(options, cancellationToken); + return await base.LoadTextAndVersionAsync(options, cancellationToken).ConfigureAwait(false); } } diff --git a/src/VisualStudio/LiveShare/Impl/Client/RoslynLSPClientService.cs b/src/VisualStudio/LiveShare/Impl/Client/RoslynLSPClientService.cs index dbb29ef7281df..a4e41d96669cc 100644 --- a/src/VisualStudio/LiveShare/Impl/Client/RoslynLSPClientService.cs +++ b/src/VisualStudio/LiveShare/Impl/Client/RoslynLSPClientService.cs @@ -26,7 +26,7 @@ internal abstract class AbstractLspClientServiceFactory : ICollaborationServiceF public LS.ILanguageServerClient ActiveLanguageServerClient { get; private set; } - public Task CreateServiceAsync(CollaborationSession collaborationSession, CancellationToken cancellationToken) + public async Task CreateServiceAsync(CollaborationSession collaborationSession, CancellationToken cancellationToken) { var languageServerGuestService = (LS.ILanguageServerGuestService)collaborationSession.GetService(typeof(LS.ILanguageServerGuestService)); @@ -90,7 +90,7 @@ public Task CreateServiceAsync(CollaborationSession colla ActiveLanguageServerClient = null; }; - return Task.FromResult(lifeTimeService); + return lifeTimeService; } protected abstract class RoslynLSPClientLifeTimeService : ICollaborationService, IDisposable diff --git a/src/VisualStudio/LiveShare/Impl/LSPSDKInitializeHandler.cs b/src/VisualStudio/LiveShare/Impl/LSPSDKInitializeHandler.cs index 23fb0dc7e581e..520242cc504e8 100644 --- a/src/VisualStudio/LiveShare/Impl/LSPSDKInitializeHandler.cs +++ b/src/VisualStudio/LiveShare/Impl/LSPSDKInitializeHandler.cs @@ -28,13 +28,13 @@ public LSPSDKInitializeHandler() { } - public Task HandleAsync(LSP.InitializeParams request, RequestContext requestContext, CancellationToken cancellationToken) + public async Task HandleAsync(LSP.InitializeParams request, RequestContext requestContext, CancellationToken cancellationToken) { var result = new LSP.InitializeResult { Capabilities = new LSP.ServerCapabilities() }; - return Task.FromResult(result); + return result; } } diff --git a/src/VisualStudio/LiveShare/Impl/LiveShareInitializeHandler.cs b/src/VisualStudio/LiveShare/Impl/LiveShareInitializeHandler.cs index 73780d3c8b3f5..ebfabf67cddc6 100644 --- a/src/VisualStudio/LiveShare/Impl/LiveShareInitializeHandler.cs +++ b/src/VisualStudio/LiveShare/Impl/LiveShareInitializeHandler.cs @@ -25,8 +25,8 @@ internal class LiveShareInitializeHandler : ILspRequestHandler HandleAsync(InitializeParams param, RequestContext requestContext, CancellationToken cancellationToken) - => Task.FromResult(s_initializeResult); + public async Task HandleAsync(InitializeParams param, RequestContext requestContext, CancellationToken cancellationToken) + => s_initializeResult; } [ExportLspRequestHandler(LiveShareConstants.RoslynContractName, Methods.InitializeName)] diff --git a/src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs b/src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs index a78e33358c98b..f9c51df21e6a1 100644 --- a/src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs +++ b/src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs @@ -20,8 +20,8 @@ namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests; [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class MockDocumentNavigationService() : AbstractDocumentNavigationService { - public override Task CanNavigateToPositionAsync(Workspace workspace, DocumentId documentId, int position, int virtualSpace, bool allowInvalidPosition, CancellationToken cancellationToken) - => SpecializedTasks.True; + public override async Task CanNavigateToPositionAsync(Workspace workspace, DocumentId documentId, int position, int virtualSpace, bool allowInvalidPosition, CancellationToken cancellationToken) + => true; public override Task GetLocationForPositionAsync(Workspace workspace, DocumentId documentId, int position, int virtualSpace, bool allowInvalidPosition, CancellationToken cancellationToken) => NavigableLocation.TestAccessor.Create(true); diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindowPackage.cs b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindowPackage.cs index 720f866972587..1202455fe078f 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindowPackage.cs +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindowPackage.cs @@ -111,8 +111,8 @@ protected override string GetToolWindowTitle(Type toolWindowType, int id) return null; } - protected override Task InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) + protected override async Task InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) { - return Task.FromResult(new object()); + return new object(); } } diff --git a/src/VisualStudio/Xaml/Impl/CodeFixes/RemoveUnnecessaryUsings/XamlRemoveUnnecessaryUsingsCodeFixProvider.cs b/src/VisualStudio/Xaml/Impl/CodeFixes/RemoveUnnecessaryUsings/XamlRemoveUnnecessaryUsingsCodeFixProvider.cs index 6890bcc6c0d57..09ae6dbfccf24 100644 --- a/src/VisualStudio/Xaml/Impl/CodeFixes/RemoveUnnecessaryUsings/XamlRemoveUnnecessaryUsingsCodeFixProvider.cs +++ b/src/VisualStudio/Xaml/Impl/CodeFixes/RemoveUnnecessaryUsings/XamlRemoveUnnecessaryUsingsCodeFixProvider.cs @@ -40,7 +40,7 @@ public override FixAllProvider GetFixAllProvider() return null; } - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( CodeAction.Create( @@ -48,7 +48,6 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) c => RemoveUnnecessaryImportsAsync(context.Document, c), nameof(Resources.RemoveUnnecessaryNamespaces)), context.Diagnostics); - return Task.CompletedTask; } private static async Task RemoveUnnecessaryImportsAsync( diff --git a/src/VisualStudio/Xaml/Impl/Features/InlineRename/XamlEditorInlineRenameService.cs b/src/VisualStudio/Xaml/Impl/Features/InlineRename/XamlEditorInlineRenameService.cs index 05afdafdff8ca..a82ad035e0047 100644 --- a/src/VisualStudio/Xaml/Impl/Features/InlineRename/XamlEditorInlineRenameService.cs +++ b/src/VisualStudio/Xaml/Impl/Features/InlineRename/XamlEditorInlineRenameService.cs @@ -32,9 +32,9 @@ public XamlEditorInlineRenameService(IXamlRenameInfoService renameService) public bool IsEnabled => true; - public Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) + public async Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) { - return Task.FromResult(ImmutableDictionary>.Empty); + return ImmutableDictionary>.Empty; } public async Task GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) diff --git a/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs b/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs index d0bed3f4f5309..343bd759a0530 100644 --- a/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs +++ b/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs @@ -752,8 +752,8 @@ public static NoChangeAction Create( CodeActionPriority priority = CodeActionPriority.Default) => new(title, equivalenceKey, priority, createdFromFactoryMethod: true); - protected sealed override Task GetChangedSolutionAsync(IProgress progress, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + protected sealed override async Task GetChangedSolutionAsync(IProgress progress, CancellationToken cancellationToken) + => null; } #endregion diff --git a/src/Workspaces/Core/Portable/CodeActions/CodeActionWithOptions.cs b/src/Workspaces/Core/Portable/CodeActions/CodeActionWithOptions.cs index 0f8c3b5471b5c..a482e4ee9c882 100644 --- a/src/Workspaces/Core/Portable/CodeActions/CodeActionWithOptions.cs +++ b/src/Workspaces/Core/Portable/CodeActions/CodeActionWithOptions.cs @@ -63,8 +63,8 @@ private protected sealed override async Task /// /// An object instance returned from a call to . /// A cancellation token. - protected virtual Task> ComputeOperationsAsync(object options, CancellationToken cancellationToken) - => SpecializedTasks.EmptyEnumerable(); + protected virtual async Task> ComputeOperationsAsync(object options, CancellationToken cancellationToken) + => []; /// /// Override this method to compute the operations that implement this . Prefer @@ -74,6 +74,6 @@ protected virtual Task> ComputeOperationsAsync( protected virtual Task> ComputeOperationsAsync(object options, IProgress progress, CancellationToken cancellationToken) => ComputeOperationsAsync(options, cancellationToken); - protected override Task> ComputeOperationsAsync(CancellationToken cancellationToken) - => SpecializedTasks.EmptyEnumerable(); + protected override async Task> ComputeOperationsAsync(CancellationToken cancellationToken) + => []; } diff --git a/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs b/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs index 472c72ec61d23..59473aa8c9e9c 100644 --- a/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs +++ b/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs @@ -40,8 +40,8 @@ public sealed class ApplyChangesOperation(Solution changedSolution) : CodeAction public override void Apply(Workspace workspace, CancellationToken cancellationToken) => workspace.TryApplyChanges(ChangedSolution, CodeAnalysisProgress.None); - internal sealed override Task TryApplyAsync(Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) - => Task.FromResult(ApplyOrMergeChanges(workspace, originalSolution, ChangedSolution, progressTracker, cancellationToken)); + internal sealed override async Task TryApplyAsync(Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) + => ApplyOrMergeChanges(workspace, originalSolution, ChangedSolution, progressTracker, cancellationToken); internal static bool ApplyOrMergeChanges( Workspace workspace, diff --git a/src/Workspaces/Core/Portable/CodeActions/Operations/CodeActionOperation.cs b/src/Workspaces/Core/Portable/CodeActions/Operations/CodeActionOperation.cs index 1b42c22b424e9..cd751e5107a06 100644 --- a/src/Workspaces/Core/Portable/CodeActions/Operations/CodeActionOperation.cs +++ b/src/Workspaces/Core/Portable/CodeActions/Operations/CodeActionOperation.cs @@ -31,12 +31,12 @@ public virtual void Apply(Workspace workspace, CancellationToken cancellationTok /// Called by the host environment to apply the effect of the operation. /// This method is guaranteed to be called on the UI thread. /// - internal virtual Task TryApplyAsync(Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) + internal virtual async Task TryApplyAsync(Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) { // It is a requirement that this method be called on the UI thread. So it's safe for us to call // into .Apply without any threading operations here. this.Apply(workspace, cancellationToken); - return SpecializedTasks.True; + return true; } /// diff --git a/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs b/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs index ea4943c2ef085..b2b376f1839ff 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs @@ -19,9 +19,9 @@ internal sealed class SimplificationCodeCleanupProvider : ICodeCleanupProvider public Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, CancellationToken cancellationToken) => Simplifier.ReduceAsync(document, spans, options.SimplifierOptions, cancellationToken); - public Task CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, SolutionServices services, CancellationToken cancellationToken) + public async Task CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, SolutionServices services, CancellationToken cancellationToken) { // Simplifier doesn't work without semantic information - return Task.FromResult(root); + return root; } } diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllState.FixMultipleDiagnosticProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllState.FixMultipleDiagnosticProvider.cs index d300d1999f1eb..af06f65d38d4f 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllState.FixMultipleDiagnosticProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllState.FixMultipleDiagnosticProvider.cs @@ -33,7 +33,7 @@ public FixMultipleDiagnosticProvider(ImmutableDictionary>.Empty; } - public override Task> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) + public override async Task> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) { var allDiagnosticsBuilder = ArrayBuilder.GetInstance(); ImmutableArray diagnostics; @@ -53,27 +53,27 @@ public override Task> GetAllDiagnosticsAsync(Project pro allDiagnosticsBuilder.AddRange(diagnostics); } - return Task.FromResult>(allDiagnosticsBuilder.ToImmutableAndFree()); + return allDiagnosticsBuilder.ToImmutableAndFree(); } - public override Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) + public override async Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) { if (DocumentDiagnosticsMap.TryGetValue(document, out var diagnostics)) { - return Task.FromResult>(diagnostics); + return diagnostics; } - return SpecializedTasks.EmptyEnumerable(); + return []; } - public override Task> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) + public override async Task> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) { if (ProjectDiagnosticsMap.TryGetValue(project, out var diagnostics)) { - return Task.FromResult>(diagnostics); + return diagnostics; } - return SpecializedTasks.EmptyEnumerable(); + return []; } } } diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/NoOpFixAllProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/NoOpFixAllProvider.cs index 34003ef3452e4..48536883db552 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/NoOpFixAllProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/NoOpFixAllProvider.cs @@ -22,6 +22,6 @@ private NoOpFixAllProvider() { } - public override Task GetFixAsync(FixAllContext fixAllContext) - => Task.FromResult(null); + public override async Task GetFixAsync(FixAllContext fixAllContext) + => null; } diff --git a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs index bd3b899996941..e7ce2878139e0 100644 --- a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs +++ b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs @@ -44,7 +44,7 @@ FixAllScope.Document or FixAllScope.ContainingMember or FixAllScope.ContainingTy return null; return CodeAction.Create( - title, (_, _) => Task.FromResult(solution), equivalenceKey: null, CodeActionPriority.Default, fixAllContext.State.FixAllProvider.Cleanup); + title, async (_, _) => solution, equivalenceKey: null, CodeActionPriority.Default, fixAllContext.State.FixAllProvider.Cleanup); } private static Task GetDocumentFixesAsync( diff --git a/src/Workspaces/Core/Portable/Diagnostics/DocumentDiagnosticAnalyzer.cs b/src/Workspaces/Core/Portable/Diagnostics/DocumentDiagnosticAnalyzer.cs index 9cb666d29f30f..72d29750941b4 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/DocumentDiagnosticAnalyzer.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/DocumentDiagnosticAnalyzer.cs @@ -16,11 +16,11 @@ internal abstract class DocumentDiagnosticAnalyzer : DiagnosticAnalyzer { public const int DefaultPriority = 50; - public virtual Task> AnalyzeSyntaxAsync(TextDocument textDocument, SyntaxTree? tree, CancellationToken cancellationToken) - => SpecializedTasks.EmptyImmutableArray(); + public virtual async Task> AnalyzeSyntaxAsync(TextDocument textDocument, SyntaxTree? tree, CancellationToken cancellationToken) + => []; - public virtual Task> AnalyzeSemanticsAsync(TextDocument textDocument, SyntaxTree? tree, CancellationToken cancellationToken) - => SpecializedTasks.EmptyImmutableArray(); + public virtual async Task> AnalyzeSemanticsAsync(TextDocument textDocument, SyntaxTree? tree, CancellationToken cancellationToken) + => []; /// /// it is not allowed one to implement both DocumentDiagnosticAnalyzer and DiagnosticAnalyzer diff --git a/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs b/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs index cbd469cb79047..d5297107104b9 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs @@ -349,10 +349,10 @@ public static ImmutableArray Filter( /// This checksum is also affected by the for this project. /// As such, it is not usable across different sessions of a particular host. /// - public static Task GetDiagnosticChecksumAsync(this Project? project, CancellationToken cancellationToken) + public static async Task GetDiagnosticChecksumAsync(this Project? project, CancellationToken cancellationToken) { if (project is null) - return SpecializedTasks.Default(); + return default(Checksum); var lazyChecksum = s_projectToDiagnosticChecksum.GetValue( project, @@ -360,7 +360,7 @@ public static Task GetDiagnosticChecksumAsync(this Project? project, C static (project, cancellationToken) => ComputeDiagnosticChecksumAsync(project, cancellationToken), project)); - return lazyChecksum.GetValueAsync(cancellationToken); + return await lazyChecksum.GetValueAsync(cancellationToken).ConfigureAwait(false); static async Task ComputeDiagnosticChecksumAsync(Project project, CancellationToken cancellationToken) { diff --git a/src/Workspaces/Core/Portable/Editing/SymbolEditor.cs b/src/Workspaces/Core/Portable/Editing/SymbolEditor.cs index 3fc98f00b8f0b..9ca9c86b72177 100644 --- a/src/Workspaces/Core/Portable/Editing/SymbolEditor.cs +++ b/src/Workspaces/Core/Portable/Editing/SymbolEditor.cs @@ -260,10 +260,9 @@ public Task EditOneDeclarationAsync( { return this.EditOneDeclarationAsync( symbol, - (e, d, c) => + async (e, d, c) => { editAction(e, d); - return Task.CompletedTask; }, cancellationToken); } @@ -351,10 +350,9 @@ public Task EditOneDeclarationAsync( return this.EditOneDeclarationAsync( symbol, location, - (e, d, c) => + async (e, d, c) => { editAction(e, d); - return Task.CompletedTask; }, cancellationToken); } @@ -434,10 +432,9 @@ public Task EditOneDeclarationAsync( return this.EditOneDeclarationAsync( symbol, member, - (e, d, c) => + async (e, d, c) => { editAction(e, d); - return Task.CompletedTask; }, cancellationToken); } @@ -515,10 +512,9 @@ public Task EditAllDeclarationsAsync( { return this.EditAllDeclarationsAsync( symbol, - (e, d, c) => + async (e, d, c) => { editAction(e, d); - return Task.CompletedTask; }, cancellationToken); } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedClasses.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedClasses.cs index 0d14dd1197a7d..1c6e4e1d355b1 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedClasses.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedClasses.cs @@ -12,7 +12,7 @@ namespace Microsoft.CodeAnalysis.FindSymbols; internal static partial class DependentTypeFinder { - private static Task> FindDerivedClassesInCurrentProcessAsync( + private static async Task> FindDerivedClassesInCurrentProcessAsync( INamedTypeSymbol type, Solution solution, IImmutableSet? projects, @@ -24,13 +24,13 @@ private static Task> FindDerivedClassesInCurren static bool TypeMatches(INamedTypeSymbol type, HashSet set) => TypeHasBaseTypeInSet(type, set); - return DescendInheritanceTreeAsync(type, solution, projects, + return await DescendInheritanceTreeAsync(type, solution, projects, typeMatches: TypeMatches, shouldContinueSearching: s_isNonSealedClass, transitive: transitive, - cancellationToken: cancellationToken); + cancellationToken: cancellationToken).ConfigureAwait(false); } - return SpecializedTasks.EmptyImmutableArray(); + return []; } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedInterfaces.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedInterfaces.cs index 40e155a7d09b2..eb62c6c38c171 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedInterfaces.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedInterfaces.cs @@ -12,7 +12,7 @@ namespace Microsoft.CodeAnalysis.FindSymbols; internal static partial class DependentTypeFinder { - private static Task> FindDerivedInterfacesInCurrentProcessAsync( + private static async Task> FindDerivedInterfacesInCurrentProcessAsync( INamedTypeSymbol type, Solution solution, IImmutableSet? projects, @@ -25,13 +25,13 @@ private static Task> FindDerivedInterfacesInCur static bool TypeMatches(INamedTypeSymbol type, HashSet set) => s_isInterface(type) && TypeHasInterfaceInSet(type, set); - return DescendInheritanceTreeAsync(type, solution, projects, + return await DescendInheritanceTreeAsync(type, solution, projects, typeMatches: TypeMatches, shouldContinueSearching: s_isInterface, transitive: transitive, - cancellationToken: cancellationToken); + cancellationToken: cancellationToken).ConfigureAwait(false); } - return SpecializedTasks.EmptyImmutableArray(); + return []; } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs index 90189a63e9875..051f3e148c990 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs @@ -21,11 +21,10 @@ private sealed class NonCascadingSymbolSet(FindReferencesSearchEngine engine, Me public override ImmutableArray GetAllSymbols() => _symbols; - public override Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken) + public override async Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken) { // Nothing to do here. We're in a non-cascading scenario, so even as we encounter a new project we // don't have to figure out what new symbols may be found. - return Task.CompletedTask; } } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.cs index 9fda34d3981d9..2c02f5b714830 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.cs @@ -301,7 +301,7 @@ private async ValueTask ProcessDocumentAsync( await Parallel.ForEachAsync( symbolsToSearchFor, GetParallelOptions(cancellationToken), - (kvp, cancellationToken) => + async (kvp, cancellationToken) => { var (symbolToSearchFor, symbolGroup) = kvp; @@ -311,7 +311,6 @@ await Parallel.ForEachAsync( cache, TryGet(symbolToGlobalAliases, symbolToSearchFor)); ProcessDocument(symbolToSearchFor, symbolGroup, state, onReferenceFound); - return ValueTask.CompletedTask; }).ConfigureAwait(false); return; diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine_FindReferencesInDocuments.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine_FindReferencesInDocuments.cs index 28bdfeecea888..12a3dd0c7f171 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine_FindReferencesInDocuments.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine_FindReferencesInDocuments.cs @@ -134,7 +134,7 @@ async ValueTask DirectSymbolSearchAsync(ISymbol symbol, SymbolGroup group, FindR { await ProducerConsumer.RunAsync( ProducerConsumerOptions.SingleReaderWriterOptions, - static (callback, args, cancellationToken) => + static async (callback, args, cancellationToken) => { var (@this, symbol, group, state) = args; @@ -148,8 +148,6 @@ await ProducerConsumer.RunAsync( static (finderLocation, callback) => callback(finderLocation), callback, @this._options, cancellationToken); } - - return Task.CompletedTask; }, consumeItems: static async (values, args, cancellationToken) => { diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractMemberScopedReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractMemberScopedReferenceFinder.cs index 1c194904c1ca4..cdddde2c58f9e 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractMemberScopedReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractMemberScopedReferenceFinder.cs @@ -24,7 +24,7 @@ protected abstract bool TokensMatch( protected sealed override bool CanFind(TSymbol symbol) => true; - protected sealed override Task DetermineDocumentsToSearchAsync( + protected sealed override async Task DetermineDocumentsToSearchAsync( TSymbol symbol, HashSet? globalAliases, Project project, @@ -36,17 +36,16 @@ protected sealed override Task DetermineDocumentsToSearchAsync( { var location = symbol.Locations.FirstOrDefault(); if (location == null || !location.IsInSource) - return Task.CompletedTask; + return; var document = project.GetDocument(location.SourceTree); if (document == null) - return Task.CompletedTask; + return; if (documents != null && !documents.Contains(document)) - return Task.CompletedTask; + return; processResult(document, processResultData); - return Task.CompletedTask; } protected sealed override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs index fcc624121fa30..87619f7d9a253 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs @@ -144,7 +144,7 @@ protected static Task FindDocumentsWithGlobalSuppressMessageAttributeAsync index.ContainsGlobalSuppressMessageAttribute, processResult, processResultData, cancellationToken); } - protected static Task FindDocumentsAsync( + protected static async Task FindDocumentsAsync( Project project, IImmutableSet? documents, PredefinedType predefinedType, @@ -153,10 +153,10 @@ protected static Task FindDocumentsAsync( CancellationToken cancellationToken) { if (predefinedType == PredefinedType.None) - return Task.CompletedTask; + return; - return FindDocumentsWithPredicateAsync( - project, documents, static (index, predefinedType) => index.ContainsPredefinedType(predefinedType), predefinedType, processResult, processResultData, cancellationToken); + await FindDocumentsWithPredicateAsync( + project, documents, static (index, predefinedType) => index.ContainsPredefinedType(predefinedType), predefinedType, processResult, processResultData, cancellationToken).ConfigureAwait(false); } protected static bool IdentifiersMatch(ISyntaxFactsService syntaxFacts, string name, SyntaxToken token) @@ -666,10 +666,10 @@ protected abstract void FindReferencesInDocument( Action processResult, TData processResultData, FindReferencesSearchOptions options, CancellationToken cancellationToken); - protected virtual Task> DetermineGlobalAliasesAsync( + protected virtual async Task> DetermineGlobalAliasesAsync( TSymbol symbol, Project project, CancellationToken cancellationToken) { - return SpecializedTasks.EmptyImmutableArray(); + return []; } public sealed override Task> DetermineGlobalAliasesAsync( @@ -680,15 +680,13 @@ public sealed override Task> DetermineGlobalAliasesAsync( : SpecializedTasks.EmptyImmutableArray(); } - public sealed override Task DetermineDocumentsToSearchAsync( + public sealed override async Task DetermineDocumentsToSearchAsync( ISymbol symbol, HashSet? globalAliases, Project project, IImmutableSet? documents, Action processResult, TData processResultData, FindReferencesSearchOptions options, CancellationToken cancellationToken) { if (symbol is TSymbol typedSymbol && CanFind(typedSymbol)) - return DetermineDocumentsToSearchAsync(typedSymbol, globalAliases, project, documents, processResult, processResultData, options, cancellationToken); - - return Task.CompletedTask; + await DetermineDocumentsToSearchAsync(typedSymbol, globalAliases, project, documents, processResult, processResultData, options, cancellationToken).ConfigureAwait(false); } public sealed override void FindReferencesInDocument( @@ -698,23 +696,23 @@ public sealed override void FindReferencesInDocument( FindReferencesInDocument(typedSymbol, state, processResult, processResultData, options, cancellationToken); } - public sealed override ValueTask> DetermineCascadedSymbolsAsync( + public sealed override async ValueTask> DetermineCascadedSymbolsAsync( ISymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { if (options.Cascade && symbol is TSymbol typedSymbol && CanFind(typedSymbol)) { - return DetermineCascadedSymbolsAsync(typedSymbol, solution, options, cancellationToken); + return await DetermineCascadedSymbolsAsync(typedSymbol, solution, options, cancellationToken).ConfigureAwait(false); } - return new([]); + return []; } - protected virtual ValueTask> DetermineCascadedSymbolsAsync( + protected virtual async ValueTask> DetermineCascadedSymbolsAsync( TSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { - return new([]); + return []; } protected static void FindReferencesInDocumentUsingSymbolName( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AliasSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AliasSymbolReferenceFinder.cs index 5acaa790afd3d..201318e2717e8 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AliasSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AliasSymbolReferenceFinder.cs @@ -21,7 +21,7 @@ private AliasSymbolReferenceFinder() protected override bool CanFind(IAliasSymbol symbol) => true; - protected override Task DetermineDocumentsToSearchAsync( + protected override async Task DetermineDocumentsToSearchAsync( IAliasSymbol symbol, HashSet? globalAliases, Project project, @@ -37,8 +37,6 @@ protected override Task DetermineDocumentsToSearchAsync( if (document?.Project == project) processResult(document, processResultData); } - - return Task.CompletedTask; } protected override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorSymbolReferenceFinder.cs index 574fdca8ab760..349e83213f182 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorSymbolReferenceFinder.cs @@ -25,12 +25,12 @@ private ConstructorSymbolReferenceFinder() protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind is MethodKind.Constructor or MethodKind.StaticConstructor; - protected override ValueTask> DetermineCascadedSymbolsAsync(IMethodSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) + protected override async ValueTask> DetermineCascadedSymbolsAsync(IMethodSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { if (symbol.MethodKind is MethodKind.Constructor) - return new(GetOtherPartsOfPartial(symbol)); + return GetOtherPartsOfPartial(symbol); - return new([]); + return []; } private static ImmutableArray GetOtherPartsOfPartial(IMethodSymbol symbol) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/CrefTypeParameterSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/CrefTypeParameterSymbolReferenceFinder.cs index da5c9354a7339..56e2b563e08b9 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/CrefTypeParameterSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/CrefTypeParameterSymbolReferenceFinder.cs @@ -24,7 +24,7 @@ private CrefTypeParameterSymbolReferenceFinder() protected override bool CanFind(ITypeParameterSymbol symbol) => symbol.TypeParameterKind == TypeParameterKind.Cref; - protected override Task DetermineDocumentsToSearchAsync( + protected override async Task DetermineDocumentsToSearchAsync( ITypeParameterSymbol symbol, HashSet? globalAliases, Project project, @@ -40,8 +40,6 @@ protected override Task DetermineDocumentsToSearchAsync( if (document != null) processResult(document, processResultData); } - - return Task.CompletedTask; } protected override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/DestructorSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/DestructorSymbolReferenceFinder.cs index 35741d81ce547..953b3ac880336 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/DestructorSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/DestructorSymbolReferenceFinder.cs @@ -15,7 +15,7 @@ internal sealed class DestructorSymbolReferenceFinder : AbstractReferenceFinder< protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind == MethodKind.Destructor; - protected override Task DetermineDocumentsToSearchAsync( + protected override async Task DetermineDocumentsToSearchAsync( IMethodSymbol symbol, HashSet? globalAliases, Project project, @@ -25,7 +25,6 @@ protected override Task DetermineDocumentsToSearchAsync( FindReferencesSearchOptions options, CancellationToken cancellationToken) { - return Task.CompletedTask; } protected override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs index 611c8a6476e0b..2c511322fe574 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs @@ -17,7 +17,7 @@ internal sealed class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEve protected override bool CanFind(IEventSymbol symbol) => true; - protected sealed override ValueTask> DetermineCascadedSymbolsAsync( + protected sealed override async ValueTask> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -32,7 +32,7 @@ protected sealed override ValueTask> DetermineCascadedSy .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray(); - return new([.. GetOtherPartsOfPartial(symbol), .. backingFields, .. associatedNamedTypes]); + return [.. GetOtherPartsOfPartial(symbol), .. backingFields, .. associatedNamedTypes]; } private static ImmutableArray GetOtherPartsOfPartial(IEventSymbol symbol) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ExplicitInterfaceMethodReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ExplicitInterfaceMethodReferenceFinder.cs index 888729ebfd1a7..d8e14c0435b7f 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ExplicitInterfaceMethodReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ExplicitInterfaceMethodReferenceFinder.cs @@ -15,7 +15,7 @@ internal sealed class ExplicitInterfaceMethodReferenceFinder : AbstractReference protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind == MethodKind.ExplicitInterfaceImplementation; - protected sealed override Task DetermineDocumentsToSearchAsync( + protected sealed override async Task DetermineDocumentsToSearchAsync( IMethodSymbol symbol, HashSet? globalAliases, Project project, @@ -26,7 +26,6 @@ protected sealed override Task DetermineDocumentsToSearchAsync( CancellationToken cancellationToken) { // An explicit method can't be referenced anywhere. - return Task.CompletedTask; } protected sealed override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs index f929bc1c580d6..eb22c3ce7316c 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs @@ -23,7 +23,7 @@ private MethodTypeParameterSymbolReferenceFinder() protected override bool CanFind(ITypeParameterSymbol symbol) => symbol.TypeParameterKind == TypeParameterKind.Method; - protected override ValueTask> DetermineCascadedSymbolsAsync( + protected override async ValueTask> DetermineCascadedSymbolsAsync( ITypeParameterSymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -35,13 +35,13 @@ protected override ValueTask> DetermineCascadedSymbolsAs if (ordinal >= 0) { if (method.PartialDefinitionPart != null && ordinal < method.PartialDefinitionPart.TypeParameters.Length) - return new([method.PartialDefinitionPart.TypeParameters[ordinal]]); + return [method.PartialDefinitionPart.TypeParameters[ordinal]]; if (method.PartialImplementationPart != null && ordinal < method.PartialImplementationPart.TypeParameters.Length) - return new([method.PartialImplementationPart.TypeParameters[ordinal]]); + return [method.PartialImplementationPart.TypeParameters[ordinal]]; } - return new([]); + return []; } protected sealed override Task DetermineDocumentsToSearchAsync( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/NamedTypeSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/NamedTypeSymbolReferenceFinder.cs index e94f628cce45d..b68b2fd47e894 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/NamedTypeSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/NamedTypeSymbolReferenceFinder.cs @@ -25,7 +25,7 @@ protected override Task> DetermineGlobalAliasesAsync(INam return GetAllMatchingGlobalAliasNamesAsync(project, symbol.Name, symbol.Arity, cancellationToken); } - protected override ValueTask> DetermineCascadedSymbolsAsync( + protected override async ValueTask> DetermineCascadedSymbolsAsync( INamedTypeSymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -42,7 +42,7 @@ protected override ValueTask> DetermineCascadedSymbolsAs // cascade to destructor Add(result, symbol.GetMembers(WellKnownMemberNames.DestructorName)); - return new(result.ToImmutable()); + return result.ToImmutable(); } private static void Add(ArrayBuilder result, ImmutableArray enumerable) where TSymbol : ISymbol diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OperatorSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OperatorSymbolReferenceFinder.cs index a7ec78f9f8280..41c8a1721779c 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OperatorSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OperatorSymbolReferenceFinder.cs @@ -33,7 +33,7 @@ protected sealed override async Task DetermineDocumentsToSearchAsync( await FindDocumentsWithGlobalSuppressMessageAttributeAsync(project, documents, processResult, processResultData, cancellationToken).ConfigureAwait(false); } - private static Task FindDocumentsAsync( + private static async Task FindDocumentsAsync( Project project, IImmutableSet? documents, PredefinedOperator op, @@ -42,10 +42,10 @@ private static Task FindDocumentsAsync( CancellationToken cancellationToken) { if (op == PredefinedOperator.None) - return Task.CompletedTask; + return; - return FindDocumentsWithPredicateAsync( - project, documents, static (index, op) => index.ContainsPredefinedOperator(op), op, processResult, processResultData, cancellationToken); + await FindDocumentsWithPredicateAsync( + project, documents, static (index, op) => index.ContainsPredefinedOperator(op), op, processResult, processResultData, cancellationToken).ConfigureAwait(false); } protected sealed override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OrdinaryMethodReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OrdinaryMethodReferenceFinder.cs index eb3ae5d47aa1a..364d88d78e858 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OrdinaryMethodReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OrdinaryMethodReferenceFinder.cs @@ -20,7 +20,7 @@ MethodKind.DeclareMethod or MethodKind.ReducedExtension or MethodKind.LocalFunction; - protected override ValueTask> DetermineCascadedSymbolsAsync( + protected override async ValueTask> DetermineCascadedSymbolsAsync( IMethodSymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -29,7 +29,7 @@ protected override ValueTask> DetermineCascadedSymbolsAs // If it's a delegate method, then cascade to the type as well. These guys are // practically equivalent for users. if (symbol.ContainingType.TypeKind == TypeKind.Delegate) - return new([symbol.ContainingType]); + return [symbol.ContainingType]; using var _ = ArrayBuilder.GetInstance(out var result); @@ -40,7 +40,7 @@ protected override ValueTask> DetermineCascadedSymbolsAs CascadeFromExtensionImplementation(symbol, result); - return new(result.ToImmutableAndClear()); + return result.ToImmutableAndClear(); } private static void CascadeFromExtensionImplementation(IMethodSymbol symbol, ArrayBuilder result) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertyAccessorSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertyAccessorSymbolReferenceFinder.cs index 3799f7231bfaa..7bcc55d8e1cef 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertyAccessorSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertyAccessorSymbolReferenceFinder.cs @@ -17,7 +17,7 @@ internal sealed class PropertyAccessorSymbolReferenceFinder : AbstractMethodOrPr protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind.IsPropertyAccessor(); - protected override ValueTask> DetermineCascadedSymbolsAsync( + protected override async ValueTask> DetermineCascadedSymbolsAsync( IMethodSymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -33,7 +33,7 @@ protected override ValueTask> DetermineCascadedSymbolsAs // If the given symbol is an extension accessor, cascade to its implementation method result.AddIfNotNull(symbol.AssociatedExtensionImplementation); - return new(result.ToImmutableAndClear()); + return result.ToImmutableAndClear(); } protected override async Task DetermineDocumentsToSearchAsync( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertySymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertySymbolReferenceFinder.cs index 1132babf80056..a453c554d724b 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertySymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertySymbolReferenceFinder.cs @@ -27,7 +27,7 @@ private PropertySymbolReferenceFinder() protected override bool CanFind(IPropertySymbol symbol) => true; - protected override ValueTask> DetermineCascadedSymbolsAsync( + protected override async ValueTask> DetermineCascadedSymbolsAsync( IPropertySymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -40,7 +40,7 @@ protected override ValueTask> DetermineCascadedSymbolsAs CascadeToAccessors(symbol, result); CascadeToPrimaryConstructorParameters(symbol, result, cancellationToken); - return new(result.ToImmutable()); + return result.ToImmutable(); } private static void CascadeToOtherPartOfPartial(IPropertySymbol symbol, ArrayBuilder result) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/StreamingFindReferencesProgress.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/StreamingFindReferencesProgress.cs index 6e9c6f8336976..fc5e3c0528103 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/StreamingFindReferencesProgress.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/StreamingFindReferencesProgress.cs @@ -25,27 +25,23 @@ internal sealed class StreamingFindReferencesProgressAdapter : IStreamingFindRef public StreamingFindReferencesProgressAdapter(IFindReferencesProgress progress) { _progress = progress; - ProgressTracker = new StreamingProgressTracker((current, max, ct) => + ProgressTracker = new StreamingProgressTracker(async (current, max, ct) => { _progress.ReportProgress(current, max); - return default; }); } - public ValueTask OnCompletedAsync(CancellationToken cancellationToken) + public async ValueTask OnCompletedAsync(CancellationToken cancellationToken) { _progress.OnCompleted(); - return default; } - public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) + public async ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) { try { foreach (var symbol in group.Symbols) _progress.OnDefinitionFound(symbol); - - return default; } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { @@ -53,17 +49,14 @@ public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken can } } - public ValueTask OnReferencesFoundAsync(ImmutableArray<(SymbolGroup group, ISymbol symbol, ReferenceLocation location)> references, CancellationToken cancellationToken) + public async ValueTask OnReferencesFoundAsync(ImmutableArray<(SymbolGroup group, ISymbol symbol, ReferenceLocation location)> references, CancellationToken cancellationToken) { foreach (var (_, symbol, location) in references) _progress.OnReferenceFound(symbol, location); - - return ValueTask.CompletedTask; } - public ValueTask OnStartedAsync(CancellationToken cancellationToken) + public async ValueTask OnStartedAsync(CancellationToken cancellationToken) { _progress.OnStarted(); - return default; } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs index 408f0f9923ce7..5b1af0e92999b 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs @@ -183,7 +183,7 @@ static async Task CreateMetadataSymbolTreeInfoAsync( arg.services, arg.solutionKey, arg.checksum, - createAsync: checksum => new ValueTask(new MetadataInfoCreator(checksum, GetMetadataNoThrow(arg.reference)).Create()), + createAsync: async checksum => new MetadataInfoCreator(checksum, GetMetadataNoThrow(arg.reference)).Create(), keySuffix: GetMetadataKeySuffix(arg.reference), cancellationToken), arg: (services, solutionKey, checksum, reference))); diff --git a/src/Workspaces/Core/Portable/Recommendations/Recommender.cs b/src/Workspaces/Core/Portable/Recommendations/Recommender.cs index fd8919d2a13d1..7a24a397850f5 100644 --- a/src/Workspaces/Core/Portable/Recommendations/Recommender.cs +++ b/src/Workspaces/Core/Portable/Recommendations/Recommender.cs @@ -32,14 +32,14 @@ public static IEnumerable GetRecommendedSymbolsAtPosition( } [Obsolete("Use GetRecommendedSymbolsAtPositionAsync(Document, ...)")] - public static Task> GetRecommendedSymbolsAtPositionAsync( + public static async Task> GetRecommendedSymbolsAtPositionAsync( SemanticModel semanticModel, int position, Workspace workspace, OptionSet? options = null, CancellationToken cancellationToken = default) { - return Task.FromResult(GetRecommendedSymbolsAtPosition(semanticModel, position, workspace, options, cancellationToken)); + return GetRecommendedSymbolsAtPosition(semanticModel, position, workspace, options, cancellationToken); } public static async Task> GetRecommendedSymbolsAtPositionAsync( diff --git a/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs b/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs index 433dca5a99a23..6f2b4b234fb22 100644 --- a/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs +++ b/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs @@ -19,37 +19,37 @@ internal abstract class RemoteHostClient : IDisposable { public abstract void Dispose(); - public static Task WaitForClientCreationAsync(Workspace workspace, CancellationToken cancellationToken) + public static async Task WaitForClientCreationAsync(Workspace workspace, CancellationToken cancellationToken) { var service = workspace.Services.GetService(); if (service == null) - return Task.CompletedTask; + return; - return service.WaitForClientCreationAsync(cancellationToken); + await service.WaitForClientCreationAsync(cancellationToken).ConfigureAwait(false); } - public static Task TryGetClientAsync(Project project, CancellationToken cancellationToken) + public static async Task TryGetClientAsync(Project project, CancellationToken cancellationToken) { if (!RemoteSupportedLanguages.IsSupported(project.Language)) { - return SpecializedTasks.Null(); + return null; } - return TryGetClientAsync(project.Solution.Services, cancellationToken); + return await TryGetClientAsync(project.Solution.Services, cancellationToken).ConfigureAwait(false); } public static Task TryGetClientAsync(Workspace workspace, CancellationToken cancellationToken) => TryGetClientAsync(workspace.Services.SolutionServices, cancellationToken); - public static Task TryGetClientAsync(SolutionServices services, CancellationToken cancellationToken) + public static async Task TryGetClientAsync(SolutionServices services, CancellationToken cancellationToken) { var service = services.GetService(); if (service == null) { - return SpecializedTasks.Null(); + return null; } - return service.TryGetRemoteHostClientAsync(cancellationToken); + return await service.TryGetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false); } public abstract RemoteServiceConnection CreateConnection(object? callbackTarget) diff --git a/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs b/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs index ed0dfbf53b914..f8637a23e25ec 100644 --- a/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs +++ b/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs @@ -40,16 +40,16 @@ public AsynchronousOperationListener(string featureName, bool enableDiagnosticTo [PerformanceSensitive( "https://github.com/dotnet/roslyn/pull/58646", Constraint = "Cannot use async/await because it produces large numbers of first-chance cancellation exceptions.")] - public Task Delay(TimeSpan delay, CancellationToken cancellationToken) + public async Task Delay(TimeSpan delay, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) - return Task.FromCanceled(cancellationToken); + return await Task.FromCanceled(cancellationToken).ConfigureAwait(false); var expeditedDelayCancellationToken = _expeditedDelayCancellationTokenSource.Token; if (expeditedDelayCancellationToken.IsCancellationRequested) { // The operation is already being expedited - return SpecializedTasks.False; + return false; } var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, expeditedDelayCancellationToken); @@ -59,28 +59,28 @@ public Task Delay(TimeSpan delay, CancellationToken cancellationToken) { cancellationTokenSource.Dispose(); if (delayTask.Status == TaskStatus.RanToCompletion) - return SpecializedTasks.True; + return true; else if (cancellationToken.IsCancellationRequested) - return Task.FromCanceled(cancellationToken); + return await Task.FromCanceled(cancellationToken).ConfigureAwait(false); else - return SpecializedTasks.False; + return false; } // Handle continuation in a local function to avoid capturing arguments when this path is avoided - return DelaySlowAsync(delayTask, cancellationTokenSource, cancellationToken); + return await DelaySlowAsync(delayTask, cancellationTokenSource, cancellationToken).ConfigureAwait(false); static Task DelaySlowAsync(Task delayTask, CancellationTokenSource cancellationTokenSourceToDispose, CancellationToken cancellationToken) { return delayTask.ContinueWith( - task => + async task => { cancellationTokenSourceToDispose.Dispose(); if (task.Status == TaskStatus.RanToCompletion) - return SpecializedTasks.True; + return true; else if (cancellationToken.IsCancellationRequested) - return Task.FromCanceled(cancellationToken); + return await Task.FromCanceled(cancellationToken).ConfigureAwait(false); else - return SpecializedTasks.False; + return false; }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs index c17666916d22d..d4884dafbad74 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs @@ -64,23 +64,23 @@ protected override string GetDatabaseFilePath(string workingFolderPath) return Path.Combine(workingFolderPath, StorageExtension, nameof(v2), PersistentStorageFileName); } - protected override ValueTask TryOpenDatabaseAsync( + protected override async ValueTask TryOpenDatabaseAsync( SolutionKey solutionKey, string workingFolderPath, string databaseFilePath, IPersistentStorageFaultInjector? faultInjector, CancellationToken cancellationToken) { if (!TryInitializeLibraries()) { // SQLite is not supported on the current platform - return new((IChecksummedPersistentStorage?)null); + return null; } if (solutionKey.FilePath == null) - return new(NoOpPersistentStorage.GetOrThrow(solutionKey, Configuration.ThrowOnFailure)); + return NoOpPersistentStorage.GetOrThrow(solutionKey, Configuration.ThrowOnFailure); - return new(SQLitePersistentStorage.TryCreate( + return SQLitePersistentStorage.TryCreate( solutionKey, workingFolderPath, databaseFilePath, asyncListener, - faultInjector)); + faultInjector); } } diff --git a/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs b/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs index 45337f28d766e..211d88014e0d9 100644 --- a/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs +++ b/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs @@ -155,12 +155,12 @@ internal sealed class ReferenceAssemblyResult( [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class DefaultSymbolSearchService() : ISymbolSearchService { - public ValueTask> FindPackagesAsync(string source, TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) - => ValueTask.FromResult(ImmutableArray.Empty); + public async ValueTask> FindPackagesAsync(string source, TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) + => ImmutableArray.Empty; - public ValueTask> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) - => ValueTask.FromResult(ImmutableArray.Empty); + public async ValueTask> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) + => ImmutableArray.Empty; - public ValueTask> FindReferenceAssembliesAsync(TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) - => ValueTask.FromResult(ImmutableArray.Empty); + public async ValueTask> FindReferenceAssembliesAsync(TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) + => ImmutableArray.Empty; } diff --git a/src/Workspaces/Core/Portable/TemporaryStorage/TrivialTemporaryStorageService.cs b/src/Workspaces/Core/Portable/TemporaryStorage/TrivialTemporaryStorageService.cs index cc0f48a32e732..7c4381c1e6d7d 100644 --- a/src/Workspaces/Core/Portable/TemporaryStorage/TrivialTemporaryStorageService.cs +++ b/src/Workspaces/Core/Portable/TemporaryStorage/TrivialTemporaryStorageService.cs @@ -32,9 +32,9 @@ public ITemporaryStorageTextHandle WriteToTemporaryStorage(SourceText text, Canc return new TextStorage(text); } - public Task WriteToTemporaryStorageAsync(SourceText text, CancellationToken cancellationToken) + public async Task WriteToTemporaryStorageAsync(SourceText text, CancellationToken cancellationToken) { - return Task.FromResult(new TextStorage(text)); + return new TextStorage(text); } private sealed class StreamStorage : ITemporaryStorageStreamHandle @@ -74,9 +74,9 @@ public SourceText ReadFromTemporaryStorage(CancellationToken cancellationToken) return _sourceText; } - public Task ReadFromTemporaryStorageAsync(CancellationToken cancellationToken) + public async Task ReadFromTemporaryStorageAsync(CancellationToken cancellationToken) { - return Task.FromResult(_sourceText); + return _sourceText; } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/DocumentExcerptHelper.cs b/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/DocumentExcerptHelper.cs index b409b22a479fc..8497e7a584f49 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/DocumentExcerptHelper.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/DocumentExcerptHelper.cs @@ -23,20 +23,20 @@ public static bool CanExcerpt(Document document) return document.DocumentServiceProvider.GetService() is not null; } - public static Task TryExcerptAsync(Document document, TextSpan span, ExcerptMode mode, ClassificationOptions classificationOptions, CancellationToken cancellationToken) + public static async Task TryExcerptAsync(Document document, TextSpan span, ExcerptMode mode, ClassificationOptions classificationOptions, CancellationToken cancellationToken) { if (document is SourceGeneratedDocument sourceGeneratedDocument && document.Project.Solution.Services.GetService() is { } sourceGeneratedExcerptService) { - return sourceGeneratedExcerptService.TryExcerptAsync(sourceGeneratedDocument, span, mode, classificationOptions, cancellationToken); + return await sourceGeneratedExcerptService.TryExcerptAsync(sourceGeneratedDocument, span, mode, classificationOptions, cancellationToken).ConfigureAwait(false); } var excerptService = document.DocumentServiceProvider.GetService(); if (excerptService == null) { - return SpecializedTasks.Default(); + return null; } - return excerptService.TryExcerptAsync(document, span, mode, classificationOptions, cancellationToken); + return await excerptService.TryExcerptAsync(document, span, mode, classificationOptions, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorage.cs b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorage.cs index 0af8e93ab5b28..123d9bf2315f6 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorage.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorage.cs @@ -20,68 +20,68 @@ public static IChecksummedPersistentStorage GetOrThrow(SolutionKey solutionKey, ? throw new InvalidOperationException("Database was not supported") : new NoOpPersistentStorage(solutionKey); - public Task ChecksumMatchesAsync(string name, Checksum checksum, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task ChecksumMatchesAsync(string name, Checksum checksum, CancellationToken cancellationToken) + => false; - public Task ChecksumMatchesAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task ChecksumMatchesAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) + => false; - public Task ChecksumMatchesAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task ChecksumMatchesAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) + => false; - public Task ChecksumMatchesAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task ChecksumMatchesAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) + => false; - public Task ChecksumMatchesAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task ChecksumMatchesAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) + => false; - public Task ReadStreamAsync(Document document, string name, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task ReadStreamAsync(Document document, string name, CancellationToken cancellationToken) + => null; - public Task ReadStreamAsync(Project project, string name, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task ReadStreamAsync(Project project, string name, CancellationToken cancellationToken) + => null; - public Task ReadStreamAsync(string name, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task ReadStreamAsync(string name, CancellationToken cancellationToken) + => null; - public Task ReadStreamAsync(string name, Checksum? checksum, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task ReadStreamAsync(string name, Checksum? checksum, CancellationToken cancellationToken) + => null; - public Task ReadStreamAsync(Project project, string name, Checksum? checksum, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task ReadStreamAsync(Project project, string name, Checksum? checksum, CancellationToken cancellationToken) + => null; - public Task ReadStreamAsync(Document document, string name, Checksum? checksum, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task ReadStreamAsync(Document document, string name, Checksum? checksum, CancellationToken cancellationToken) + => null; - public Task ReadStreamAsync(ProjectKey project, string name, Checksum? checksum, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task ReadStreamAsync(ProjectKey project, string name, Checksum? checksum, CancellationToken cancellationToken) + => null; - public Task ReadStreamAsync(DocumentKey document, string name, Checksum? checksum, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task ReadStreamAsync(DocumentKey document, string name, Checksum? checksum, CancellationToken cancellationToken) + => null; - public Task WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken) + => false; - public Task WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken) + => false; - public Task WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken) + => false; - public Task WriteStreamAsync(string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task WriteStreamAsync(string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) + => false; - public Task WriteStreamAsync(Project project, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task WriteStreamAsync(Project project, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) + => false; - public Task WriteStreamAsync(Document document, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task WriteStreamAsync(Document document, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) + => false; - public Task WriteStreamAsync(ProjectKey projectKey, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task WriteStreamAsync(ProjectKey projectKey, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) + => false; - public Task WriteStreamAsync(DocumentKey documentKey, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) - => SpecializedTasks.False; + public async Task WriteStreamAsync(DocumentKey documentKey, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) + => false; public readonly struct TestAccessor { diff --git a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorageService.cs b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorageService.cs index 5f5bc076f5df3..1b14a15cf1c4f 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorageService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorageService.cs @@ -22,6 +22,6 @@ public static IChecksummedPersistentStorageService GetOrThrow(IPersistentStorage ? throw new InvalidOperationException("Database was not supported") : Instance; - public ValueTask GetStorageAsync(SolutionKey solutionKey, CancellationToken cancellationToken) - => new(NoOpPersistentStorage.GetOrThrow(solutionKey, throwOnFailure: false)); + public async ValueTask GetStorageAsync(SolutionKey solutionKey, CancellationToken cancellationToken) + => NoOpPersistentStorage.GetOrThrow(solutionKey, throwOnFailure: false); } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Status/DefaultWorkspaceStatusService.cs b/src/Workspaces/Core/Portable/Workspace/Host/Status/DefaultWorkspaceStatusService.cs index 02c72cb3e4183..63921d5c1f0fe 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Status/DefaultWorkspaceStatusService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Status/DefaultWorkspaceStatusService.cs @@ -22,15 +22,14 @@ event EventHandler IWorkspaceStatusService.StatusChanged remove { } } - public Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken) + public async Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken) { // by the default, we are always fully loaded - return Task.CompletedTask; } - public Task IsFullyLoadedAsync(CancellationToken cancellationToken) + public async Task IsFullyLoadedAsync(CancellationToken cancellationToken) { // by the default, we are always fully loaded - return SpecializedTasks.True; + return true; } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs b/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs index a4e011da48238..9a3fc38b5f180 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs @@ -50,9 +50,9 @@ public Stream ReadStream(CancellationToken cancellationToken = default) return new MemoryStream(stream.GetBuffer(), 0, (int)stream.Length, writable: false); } - public Task ReadStreamAsync(CancellationToken cancellationToken = default) + public async Task ReadStreamAsync(CancellationToken cancellationToken = default) { - return Task.FromResult(ReadStream(cancellationToken)); + return ReadStream(cancellationToken); } public void WriteStream(Stream stream, CancellationToken cancellationToken = default) @@ -92,8 +92,8 @@ public void Dispose() public SourceText ReadText(CancellationToken cancellationToken = default) => _sourceText ?? throw new InvalidOperationException(); - public Task ReadTextAsync(CancellationToken cancellationToken = default) - => Task.FromResult(ReadText(cancellationToken)); + public async Task ReadTextAsync(CancellationToken cancellationToken = default) + => ReadText(cancellationToken); public void WriteText(SourceText text, CancellationToken cancellationToken = default) { @@ -107,10 +107,9 @@ public void WriteText(SourceText text, CancellationToken cancellationToken = def } } - public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default) + public async Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default) { WriteText(text, cancellationToken); - return Task.CompletedTask; } } } diff --git a/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Core.cs b/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Core.cs index 2592d94422eb8..6b6c349c0d6d7 100644 --- a/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Core.cs +++ b/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Core.cs @@ -210,7 +210,7 @@ public static async partial ValueTask> CreateI useAsync, analyzerChecksums, solutionServices, - () => Task.FromResult(references), + async () => references, cancellationToken).ConfigureAwait(false); } diff --git a/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Desktop.cs b/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Desktop.cs index 362f448ae8262..b4638bdf3a54f 100644 --- a/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Desktop.cs +++ b/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Desktop.cs @@ -21,13 +21,13 @@ namespace Microsoft.CodeAnalysis; /// internal sealed partial class IsolatedAnalyzerReferenceSet { - public static partial ValueTask> CreateIsolatedAnalyzerReferencesAsync( + public static async partial ValueTask> CreateIsolatedAnalyzerReferencesAsync( bool useAsync, ImmutableArray references, SolutionServices solutionServices, CancellationToken cancellationToken) { - return ValueTask.FromResult(references); + return references; } public static async partial ValueTask> CreateIsolatedAnalyzerReferencesAsync( diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs index ab75dacee1552..b41df54f26611 100644 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs +++ b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs @@ -664,8 +664,8 @@ public SourceTextLoader(SourceTextContainer textContainer, string? filePath) _filePath = filePath; } - public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(TextAndVersion.Create(_textContainer.CurrentText, VersionStamp.Create(), _filePath)); + public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => TextAndVersion.Create(_textContainer.CurrentText, VersionStamp.Create(), _filePath); } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs index 19d32d984b671..d2c38a34cb8f1 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs @@ -27,8 +27,8 @@ public TextLoader? TextLoader public TextAndVersion GetValue(LoadTextOptions options, CancellationToken cancellationToken) => _value; - public Task GetValueAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(_value); + public async Task GetValueAsync(LoadTextOptions options, CancellationToken cancellationToken) + => _value; public bool TryGetValue(LoadTextOptions options, [MaybeNullWhen(false)] out TextAndVersion value) { @@ -42,6 +42,6 @@ public bool TryGetVersion(LoadTextOptions options, out VersionStamp version) return true; } - public ValueTask GetVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => new(_value.Version); + public async ValueTask GetVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => _value.Version; } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs index 7b83ff5fb000d..ce4b54061fd2b 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs @@ -165,18 +165,18 @@ public bool SupportsSemanticModel /// to or may end up causing computation /// to occur at that point. /// - public Task GetSyntaxTreeAsync(CancellationToken cancellationToken = default) + public async Task GetSyntaxTreeAsync(CancellationToken cancellationToken = default) { // If the language doesn't support getting syntax trees for a document, then bail out immediately. if (!this.SupportsSyntaxTree) { - return SpecializedTasks.Null(); + return null; } // if we have a cached result task use it if (_syntaxTreeResultTask != null) { - return _syntaxTreeResultTask.AsNullable(); + return await _syntaxTreeResultTask.ConfigureAwait(false); } // check to see if we already have the tree before actually going async @@ -185,13 +185,13 @@ public bool SupportsSemanticModel // stash a completed result task for this value for the next request (to reduce extraneous allocations of tasks) // don't use the actual async task because it depends on a specific cancellation token // its okay to cache the task and hold onto the SyntaxTree, because the DocumentState already keeps the SyntaxTree alive. - Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null); + _ = Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null); - return _syntaxTreeResultTask.AsNullable(); + return await _syntaxTreeResultTask.ConfigureAwait(false); } // do it async for real. - return DocumentState.GetSyntaxTreeAsync(cancellationToken).AsTask().AsNullable(); + return await DocumentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); } internal SyntaxTree? GetSyntaxTreeSynchronously(CancellationToken cancellationToken) diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs index 53f5d0dc024c4..02c21970b852e 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs @@ -58,6 +58,6 @@ public bool TryGetVersion(LoadTextOptions options, out VersionStamp version) return version != default; } - public ValueTask GetVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => new(_version); + public async ValueTask GetVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => _version; } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs index df6641633fe30..764d65bc75496 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs @@ -251,31 +251,31 @@ private static Project CreateProject(ProjectId projectId, Solution solution) /// /// Gets a document or a source generated document in this solution with the specified document ID. /// - internal ValueTask GetDocumentAsync(DocumentId? documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default) + internal async ValueTask GetDocumentAsync(DocumentId? documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default) { var project = GetProject(documentId?.ProjectId); if (project == null) { - return default; + return null; } Contract.ThrowIfNull(documentId); - return project.GetDocumentAsync(documentId, includeSourceGenerated, cancellationToken); + return await project.GetDocumentAsync(documentId, includeSourceGenerated, cancellationToken).ConfigureAwait(false); } /// /// Gets a document, additional document, analyzer config document or a source generated document in this solution with the specified document ID. /// - internal ValueTask GetTextDocumentAsync(DocumentId? documentId, CancellationToken cancellationToken = default) + internal async ValueTask GetTextDocumentAsync(DocumentId? documentId, CancellationToken cancellationToken = default) { var project = GetProject(documentId?.ProjectId); if (project == null) { - return default; + return null; } Contract.ThrowIfNull(documentId); - return project.GetTextDocumentAsync(documentId, cancellationToken); + return await project.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); } /// @@ -304,17 +304,17 @@ private static Project CreateProject(ProjectId projectId, Solution solution) return null; } - public ValueTask GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) + public async ValueTask GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { var project = GetProject(documentId.ProjectId); if (project == null) { - return new(result: null); + return null; } else { - return project.GetSourceGeneratedDocumentAsync(documentId, cancellationToken); + return await project.GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker.cs index 7754b7924a122..9f13228131041 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker.cs @@ -213,22 +213,22 @@ public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) } } - public Task GetCompilationAsync(SolutionCompilationState compilationState, CancellationToken cancellationToken) + public async Task GetCompilationAsync(SolutionCompilationState compilationState, CancellationToken cancellationToken) { if (this.TryGetCompilation(out var compilation)) { - return Task.FromResult(compilation); + return compilation; } else if (cancellationToken.IsCancellationRequested) { // Handle early cancellation here to avoid throwing/catching cancellation exceptions in the async // state machines. This helps reduce the total number of First Chance Exceptions occurring in IDE // typing scenarios. - return Task.FromCanceled(cancellationToken); + return await Task.FromCanceled(cancellationToken).ConfigureAwait(false); } else { - return GetCompilationSlowAsync(compilationState, cancellationToken); + return await GetCompilationSlowAsync(compilationState, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SkeletonReferenceCache.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SkeletonReferenceCache.cs index 129720b03bd5f..75081bcd871b0 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SkeletonReferenceCache.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SkeletonReferenceCache.cs @@ -208,8 +208,8 @@ public readonly SkeletonReferenceCache Clone() // concurrent requests asynchronously wait for that work to be done. var lazy = s_compilationToSkeletonSet.GetValue(compilation, - compilation => AsyncLazy.Create(static (arg, cancellationToken) => - Task.FromResult(CreateSkeletonSet(arg.services, arg.compilation, cancellationToken)), + compilation => AsyncLazy.Create(static async (arg, cancellationToken) => + CreateSkeletonSet(arg.services, arg.compilation, cancellationToken), arg: (services, compilation))); return await lazy.GetValueAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.TranslationAction_Actions.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.TranslationAction_Actions.cs index 85c092e64821a..a1b490c502b4a 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.TranslationAction_Actions.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.TranslationAction_Actions.cs @@ -82,8 +82,8 @@ internal sealed class TouchAdditionalDocumentsAction( // compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; - public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => Task.FromResult(oldCompilation); + public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => oldCompilation; public override TranslationAction? TryMergeWithPrior(TranslationAction priorAction) { @@ -117,10 +117,10 @@ internal sealed class TouchAnalyzerConfigDocumentsAction( /// /// Updating editorconfig document updates . /// - public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { RoslynDebug.AssertNotNull(this.NewProjectState.CompilationOptions); - return Task.FromResult(oldCompilation.WithOptions(this.NewProjectState.CompilationOptions)); + return oldCompilation.WithOptions(this.NewProjectState.CompilationOptions); } // Updating the analyzer config optons doesn't require us to reparse trees, so we can use this to update @@ -239,10 +239,10 @@ internal sealed class ProjectCompilationOptionsAction( ProjectState oldProjectState, ProjectState newProjectState) : TranslationAction(oldProjectState, newProjectState) { - public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { Contract.ThrowIfNull(this.NewProjectState.CompilationOptions); - return Task.FromResult(oldCompilation.WithOptions(this.NewProjectState.CompilationOptions)); + return oldCompilation.WithOptions(this.NewProjectState.CompilationOptions); } // Updating the options of a compilation doesn't require us to reparse trees, so we can use this to update @@ -262,8 +262,8 @@ internal sealed class ProjectAssemblyNameAction( ProjectState newProjectState) : TranslationAction(oldProjectState, newProjectState) { - public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => Task.FromResult(oldCompilation.WithAssemblyName(NewProjectState.AssemblyName)); + public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => oldCompilation.WithAssemblyName(NewProjectState.AssemblyName); // Updating the options of a compilation doesn't require us to reparse trees, so we can use this to update // compilations with stale generated trees. @@ -285,8 +285,8 @@ internal sealed class AddOrRemoveAnalyzerReferencesAction( // compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; - public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => Task.FromResult(oldCompilation); + public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => oldCompilation; public override GeneratorDriver TransformGeneratorDriver(GeneratorDriver generatorDriver) { @@ -316,8 +316,8 @@ internal sealed class AddAdditionalDocumentsAction( // compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; - public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => Task.FromResult(oldCompilation); + public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => oldCompilation; public override GeneratorDriver TransformGeneratorDriver(GeneratorDriver generatorDriver) { @@ -336,8 +336,8 @@ internal sealed class RemoveAdditionalDocumentsAction( // compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; - public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => Task.FromResult(oldCompilation); + public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => oldCompilation; public override GeneratorDriver TransformGeneratorDriver(GeneratorDriver generatorDriver) { @@ -355,8 +355,8 @@ internal sealed class ReplaceGeneratorDriverAction( // Replacing the generator doesn't change the non-generator compilation. So we can just return the old // compilation as is. - public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => Task.FromResult(oldCompilation); + public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => oldCompilation; public override GeneratorDriver TransformGeneratorDriver(GeneratorDriver _) { diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState.cs index ab9bfa465da47..375de862ad368 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState.cs @@ -178,15 +178,15 @@ private static ITextAndVersionSource CreateTextFromLoader(SolutionServices solut return new RecoverableTextAndVersion(new LoadableTextAndVersionSource(loader, cacheResult: false), solutionServices); } - private ValueTask GetTextAndVersionAsync(CancellationToken cancellationToken) + private async ValueTask GetTextAndVersionAsync(CancellationToken cancellationToken) { if (this.TextAndVersionSource.TryGetValue(LoadTextOptions, out var textAndVersion)) { - return new ValueTask(textAndVersion); + return textAndVersion; } else { - return new ValueTask(TextAndVersionSource.GetValueAsync(LoadTextOptions, cancellationToken)); + return await TextAndVersionSource.GetValueAsync(LoadTextOptions, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.cs b/src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.cs index ac00ed9a74486..9d3e1654a3ccf 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.cs @@ -200,8 +200,8 @@ private sealed class TextDocumentLoader : TextLoader internal TextDocumentLoader(TextAndVersion textAndVersion) => _textAndVersion = textAndVersion; - public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(_textAndVersion); + public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => _textAndVersion; internal override TextAndVersion LoadTextAndVersionSynchronously(LoadTextOptions options, CancellationToken cancellationToken) => _textAndVersion; @@ -223,8 +223,8 @@ internal TextContainerLoader(SourceTextContainer container, VersionStamp version internal override string? FilePath => _filePath; - public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(LoadTextAndVersionSynchronously(options, cancellationToken)); + public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => LoadTextAndVersionSynchronously(options, cancellationToken); internal override TextAndVersion LoadTextAndVersionSynchronously(LoadTextOptions options, CancellationToken cancellationToken) => TextAndVersion.Create(_container.CurrentText, _version, _filePath); diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace.cs b/src/Workspaces/Core/Portable/Workspace/Workspace.cs index 4c32aa6986c8a..e93a13970638c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace.cs @@ -291,7 +291,9 @@ internal bool SetCurrentSolution( // Doing so under the serialization lock guarantees the same ordering of the events // as the order of the changes made to the solution. var (changeKind, projectId, documentId) = data.changeKind(oldSolution, newSolution); - data.@this.RaiseWorkspaceChangedEventAsync(changeKind, oldSolution, newSolution, projectId, documentId); + + // Fire and forget + _ = data.@this.RaiseWorkspaceChangedEventAsync(changeKind, oldSolution, newSolution, projectId, documentId); }, cancellationToken).ConfigureAwait(false); @@ -641,10 +643,13 @@ private void ClearSolution(bool reportChangeEvent) (oldSolution, _) => this.CreateSolution(oldSolution.Id), mayRaiseEvents: reportChangeEvent, onBeforeUpdate: (_, _, _) => this.ClearSolutionData(), - onAfterUpdate: (oldSolution, newSolution, _) => + onAfterUpdate: (oldSolution, newSolution, _1) => { if (reportChangeEvent) - this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionCleared, oldSolution, newSolution); + { + // Fire and forget + _ = this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionCleared, oldSolution, newSolution); + } }); } @@ -1065,7 +1070,10 @@ protected internal void OnDocumentsAdded(ImmutableArray documentIn // Raise ProjectChanged as the event type here. DocumentAdded is presumed by many callers to have a // DocumentId associated with it, and we don't want to be raising multiple events. foreach (var projectId in data.documentInfos.Select(i => i.Id.ProjectId).Distinct()) - data.@this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectChanged, oldSolution, newSolution, projectId); + { + // Fire and forget + _ = data.@this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectChanged, oldSolution, newSolution, projectId); + } }); } @@ -1341,7 +1349,8 @@ private void OnAnyDocumentTextChanged( foreach (var updatedDocumentInfo in data.updatedDocumentIds) { - data.@this.RaiseWorkspaceChangedEventAsync( + // Fire and forget + _ = data.@this.RaiseWorkspaceChangedEventAsync( data.changeKind, oldSolution, newSolution, diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs b/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs index a7b74adde521f..b173dec7be691 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs @@ -325,7 +325,7 @@ protected internal void OnDocumentContextUpdated(DocumentId documentId) } // fire and forget - this.RaiseDocumentActiveContextChangedEventAsync(container, oldActiveContextDocumentId: oldActiveContextDocumentId, newActiveContextDocumentId: documentId); + _ = this.RaiseDocumentActiveContextChangedEventAsync(container, oldActiveContextDocumentId: oldActiveContextDocumentId, newActiveContextDocumentId: documentId); } } @@ -352,10 +352,9 @@ protected void CheckDocumentIsOpen(DocumentId documentId) protected internal void OnDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true) => OnDocumentOpened(documentId, textContainer, isCurrentContext, requireDocumentPresentAndClosed: true); - internal virtual ValueTask TryOnDocumentOpenedAsync(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, CancellationToken cancellationToken) + internal virtual async ValueTask TryOnDocumentOpenedAsync(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, CancellationToken cancellationToken) { OnDocumentOpened(documentId, textContainer, isCurrentContext, requireDocumentPresentAndClosed: false); - return ValueTask.CompletedTask; } internal void OnDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, bool requireDocumentPresentAndClosed) @@ -421,7 +420,7 @@ internal void OnDocumentOpened(DocumentId documentId, SourceTextContainer textCo @this.OnDocumentTextChanged(newDoc); // Fire and forget that the workspace is changing. - @this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); + _ = @this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); // We fire 2 events on source document opened. @this.RaiseDocumentOpenedEventAsync(newDoc); @@ -610,7 +609,7 @@ private void OnAdditionalOrAnalyzerConfigDocumentOpened( data.@this.SignupForTextChanges(documentId, data.textContainer, data.isCurrentContext, data.onDocumentTextChanged); // Fire and forget. - data.@this.RaiseWorkspaceChangedEventAsync(data.workspaceChangeKind, oldSolution, newSolution, documentId: documentId); + _ = data.@this.RaiseWorkspaceChangedEventAsync(data.workspaceChangeKind, oldSolution, newSolution, documentId: documentId); // Fire and forget. var newDoc = newSolution.GetRequiredTextDocument(documentId); @@ -697,7 +696,8 @@ private protected void OnDocumentClosedEx(DocumentId documentId, TextLoader relo var newDoc = newSolution.GetRequiredDocument(documentId); @this.OnDocumentTextChanged(newDoc); - @this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); // don't wait for this + // Fire and forget + _ = @this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); // don't wait for this // We fire and forget 2 events on source document closed. @this.RaiseDocumentClosedEventAsync(newDoc); @@ -786,7 +786,8 @@ private void OnAdditionalOrAnalyzerConfigDocumentClosed( }, onAfterUpdate: static (oldSolution, newSolution, data) => { - data.@this.RaiseWorkspaceChangedEventAsync( + // Fire and forget + _ = data.@this.RaiseWorkspaceChangedEventAsync( data.workspaceChangeKind, oldSolution, newSolution, documentId: data.documentId); // don't wait for this var newDoc = newSolution.GetRequiredTextDocument(data.documentId); diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs b/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs index a3a47ce9e9ce4..2a5b3e4d4b733 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs @@ -93,13 +93,13 @@ private WorkspaceEventRegistration RegisterHandler(WorkspaceEventTyp #endregion - protected Task RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind kind, Solution oldSolution, Solution newSolution, ProjectId? projectId = null, DocumentId? documentId = null) + protected async Task RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind kind, Solution oldSolution, Solution newSolution, ProjectId? projectId = null, DocumentId? documentId = null) { if (newSolution == null) throw new ArgumentNullException(nameof(newSolution)); if (oldSolution == newSolution) - return Task.CompletedTask; + return; if (projectId == null && documentId != null) projectId = documentId.ProjectId; @@ -117,10 +117,8 @@ protected Task RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind kind, Solutio if (handlerSet.HasHandlers) { args ??= new WorkspaceChangeEventArgs(kind, oldSolution, newSolution, projectId, documentId); - return this.ScheduleTask(args, handlerSet); + await this.ScheduleTask(args, handlerSet).ConfigureAwait(false); } - - return Task.CompletedTask; } protected internal virtual void OnWorkspaceFailed(WorkspaceDiagnostic diagnostic) @@ -139,7 +137,7 @@ protected Task RaiseDocumentOpenedEventAsync(Document document) protected Task RaiseTextDocumentOpenedEventAsync(TextDocument document) => RaiseTextDocumentOpenedOrClosedEventAsync(document, new TextDocumentEventArgs(document), WorkspaceEventType.TextDocumentOpened); - private Task RaiseTextDocumentOpenedOrClosedEventAsync( + private async Task RaiseTextDocumentOpenedOrClosedEventAsync( TDocument document, TDocumentEventArgs args, WorkspaceEventType eventType) @@ -148,9 +146,7 @@ private Task RaiseTextDocumentOpenedOrClosedEventAsync throw new NotImplementedException(); - protected Task RaiseDocumentActiveContextChangedEventAsync(SourceTextContainer sourceTextContainer, DocumentId oldActiveContextDocumentId, DocumentId newActiveContextDocumentId) + protected async Task RaiseDocumentActiveContextChangedEventAsync(SourceTextContainer sourceTextContainer, DocumentId oldActiveContextDocumentId, DocumentId newActiveContextDocumentId) { if (sourceTextContainer == null || oldActiveContextDocumentId == null || newActiveContextDocumentId == null) - return Task.CompletedTask; + return; var handlerSet = GetEventHandlers(WorkspaceEventType.DocumentActiveContextChanged); if (handlerSet.HasHandlers) @@ -175,10 +171,8 @@ protected Task RaiseDocumentActiveContextChangedEventAsync(SourceTextContainer s var currentSolution = this.CurrentSolution; var args = new DocumentActiveContextChangedEventArgs(currentSolution, sourceTextContainer, oldActiveContextDocumentId, newActiveContextDocumentId); - return this.ScheduleTask(args, handlerSet); + await this.ScheduleTask(args, handlerSet).ConfigureAwait(false); } - - return Task.CompletedTask; } private EventHandlerSet GetEventHandlers(WorkspaceEventType eventType) diff --git a/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs b/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs index b43aa84cc4bb6..35c0f34534e2e 100644 --- a/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs +++ b/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs @@ -82,7 +82,7 @@ public ReplaceZeroFix(ImmutableArray replacements, bool nested) public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -105,8 +105,6 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) context.RegisterCodeFix(fix, diagnostic); } } - - return Task.CompletedTask; } private static async Task CreateChangedDocument(Document document, TextSpan sourceSpan, int replacement, CancellationToken cancellationToken) diff --git a/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs b/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs index 0e562bd597b7d..507bbce3b9854 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs @@ -396,10 +396,10 @@ private static async Task VerifyRange(string code, ImmutableArray + CleanupDocumentAsyncImpl = async (provider, document, spans, options, cancellationToken) => { provider.ExpectedResult = spans; - return Task.FromResult(document); + return document; } }; diff --git a/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs b/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs index 0a992ecb57abb..26680babb2917 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs @@ -27,6 +27,6 @@ internal sealed class MockCodeCleanupProvider : ICodeCleanupProvider public Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, CancellationToken cancellationToken) => (CleanupDocumentAsyncImpl ?? throw new NotImplementedException()).Invoke(this, document, spans, options.FormattingOptions, cancellationToken); - public Task CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, SolutionServices services, CancellationToken cancellationToken) - => Task.FromResult((CleanupNodeImpl ?? throw new NotImplementedException()).Invoke(root, spans, options, services)); + public async Task CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, SolutionServices services, CancellationToken cancellationToken) + => (CleanupNodeImpl ?? throw new NotImplementedException()).Invoke(root, spans, options, services); } diff --git a/src/Workspaces/CoreTest/Formatter/FormatterTests.cs b/src/Workspaces/CoreTest/Formatter/FormatterTests.cs index 040105af59734..7178230fe5960 100644 --- a/src/Workspaces/CoreTest/Formatter/FormatterTests.cs +++ b/src/Workspaces/CoreTest/Formatter/FormatterTests.cs @@ -38,8 +38,8 @@ public TestFormattingService() { } - public Task FormatAsync(Document document, IEnumerable? spans, LineFormattingOptions lineFormattingOptions, SyntaxFormattingOptions? syntaxFormattingOptions, CancellationToken cancellationToken) - => Task.FromResult(document.WithText(SourceText.From($"Formatted with options: {lineFormattingOptions.ToString().Replace("\r", "\\r").Replace("\n", "\\n")}"))); + public async Task FormatAsync(Document document, IEnumerable? spans, LineFormattingOptions lineFormattingOptions, SyntaxFormattingOptions? syntaxFormattingOptions, CancellationToken cancellationToken) + => document.WithText(SourceText.From($"Formatted with options: {lineFormattingOptions.ToString().Replace("\r", "\\r").Replace("\n", "\\n")}")); } [Fact] diff --git a/src/Workspaces/CoreTest/SyntaxNodeTests.cs b/src/Workspaces/CoreTest/SyntaxNodeTests.cs index 81a812676dd41..5eddfd2e26d20 100644 --- a/src/Workspaces/CoreTest/SyntaxNodeTests.cs +++ b/src/Workspaces/CoreTest/SyntaxNodeTests.cs @@ -28,10 +28,10 @@ public async Task TestReplaceOneNodeAsync() var root = tree.GetRoot(); var node = root.DescendantNodes().OfType().Single(); - var newRoot = await root.ReplaceNodesAsync([node], (o, n, c) => + var newRoot = await root.ReplaceNodesAsync([node], async (o, n, c) => { var decl = (VariableDeclaratorSyntax)n; - return Task.FromResult(decl.WithIdentifier(SyntaxFactory.Identifier("Y"))); + return decl.WithIdentifier(SyntaxFactory.Identifier("Y")); }, CancellationToken.None); var actual = newRoot.ToString(); @@ -48,22 +48,22 @@ public async Task TestReplaceNestedNodesAsync() var nodes = root.DescendantNodes().Where(n => n is VariableDeclaratorSyntax or ClassDeclarationSyntax).ToList(); var computations = 0; - var newRoot = await root.ReplaceNodesAsync(nodes, (o, n, c) => + var newRoot = await root.ReplaceNodesAsync(nodes, async (o, n, c) => { computations++; if (n is ClassDeclarationSyntax classDecl) { var id = classDecl.Identifier; - return Task.FromResult(classDecl.WithIdentifier(SyntaxFactory.Identifier(id.LeadingTrivia, id.ToString() + "1", id.TrailingTrivia))); + return classDecl.WithIdentifier(SyntaxFactory.Identifier(id.LeadingTrivia, id.ToString() + "1", id.TrailingTrivia)); } if (n is VariableDeclaratorSyntax varDecl) { var id = varDecl.Identifier; - return Task.FromResult(varDecl.WithIdentifier(SyntaxFactory.Identifier(id.LeadingTrivia, id.ToString() + "1", id.TrailingTrivia))); + return varDecl.WithIdentifier(SyntaxFactory.Identifier(id.LeadingTrivia, id.ToString() + "1", id.TrailingTrivia)); } - return Task.FromResult(n); + return n; }, CancellationToken.None); var actual = newRoot.ToString(); diff --git a/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs b/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs index 1ca298c74e810..89431b740e550 100644 --- a/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs +++ b/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs @@ -22,7 +22,7 @@ public void GetValueAsyncReturnsCompletedTaskIfAsyncComputationCompletesImmediat // Note, this test may pass even if GetValueAsync posted a task to the threadpool, since the // current thread may context switch out and allow the threadpool to complete the task before // we check the state. However, a failure here definitely indicates a bug in AsyncLazy. - var lazy = AsyncLazy.Create(static c => Task.FromResult(5)); + var lazy = AsyncLazy.Create(static async c => 5); var t = lazy.GetValueAsync(CancellationToken.None); Assert.Equal(TaskStatus.RanToCompletion, t.Status); Assert.Equal(5, t.Result); @@ -241,7 +241,7 @@ private static void CancellationDuringInlinedComputationFromGetValueOrGetValueAs }; var lazy = AsyncLazy.Create( - static (synchronousComputation, c) => Task.FromResult(synchronousComputation(c)), + static async (synchronousComputation, c) => synchronousComputation(c), includeSynchronousComputation ? static (synchronousComputation, c) => synchronousComputation(c) : null, arg: synchronousComputation); @@ -263,7 +263,7 @@ private static void CancellationDuringInlinedComputationFromGetValueOrGetValueAs [Fact] public void SynchronousRequestShouldCacheValueWithAsynchronousComputeFunction() { - var lazy = AsyncLazy.Create(static c => Task.FromResult(new object())); + var lazy = AsyncLazy.Create(static async c => new object()); var firstRequestResult = lazy.GetValue(CancellationToken.None); var secondRequestResult = lazy.GetValue(CancellationToken.None); @@ -339,7 +339,7 @@ public async Task CancelledAndReranAsynchronousComputationDoesNotBreakSynchronou Assert.Equal(TaskStatus.Canceled, asynchronousRequestToBeCancelled.Status); // Step 3: let's now let an async request run normally, producing a value - asynchronousComputation = _ => Task.FromResult("Returned from asynchronous computation: " + Guid.NewGuid()); + asynchronousComputation = async _ => "Returned from asynchronous computation: " + Guid.NewGuid(); var asynchronousRequest = lazy.GetValueAsync(CancellationToken.None); @@ -369,7 +369,7 @@ public async Task AsynchronousResultThatWasCancelledDoesNotBreakSynchronousReque var asynchronousRequestCancellationToken = new CancellationTokenSource(); var lazy = AsyncLazy.Create( - asynchronousComputeFunction: static (arg, ct) => + asynchronousComputeFunction: static async (arg, ct) => { arg.asynchronousRequestCancellationToken.Cancel(); @@ -381,7 +381,7 @@ public async Task AsynchronousResultThatWasCancelledDoesNotBreakSynchronousReque arg.asynchronousComputationReadyToComplete.Set(); arg.asynchronousComputationShouldCompleteEvent.WaitOne(); - return Task.FromResult("Returned from asynchronous computation: " + Guid.NewGuid()); + return "Returned from asynchronous computation: " + Guid.NewGuid(); }, synchronousComputeFunction: static (arg, _) => { diff --git a/src/Workspaces/CoreTestUtilities/Fakes/SimpleAssetSource.cs b/src/Workspaces/CoreTestUtilities/Fakes/SimpleAssetSource.cs index 271ab19c41819..dd2e4840fcc7a 100644 --- a/src/Workspaces/CoreTestUtilities/Fakes/SimpleAssetSource.cs +++ b/src/Workspaces/CoreTestUtilities/Fakes/SimpleAssetSource.cs @@ -17,7 +17,7 @@ namespace Microsoft.CodeAnalysis.Remote.Testing; /// internal sealed class SimpleAssetSource(ISerializerService serializerService, IReadOnlyDictionary map) : IAssetSource { - public ValueTask GetAssetsAsync( + public async ValueTask GetAssetsAsync( Checksum solutionChecksum, AssetPath assetPath, ReadOnlyMemory checksums, ISerializerService deserializerService, Action callback, TArg arg, CancellationToken cancellationToken) { foreach (var checksum in checksums.Span) @@ -37,7 +37,5 @@ public ValueTask GetAssetsAsync( Contract.ThrowIfNull(asset); callback(checksum, (T)asset, arg); } - - return ValueTask.CompletedTask; } } diff --git a/src/Workspaces/CoreTestUtilities/Remote/InProcRemostHostClient.cs b/src/Workspaces/CoreTestUtilities/Remote/InProcRemostHostClient.cs index 278245aeb2a8e..df9c1c71a7edd 100644 --- a/src/Workspaces/CoreTestUtilities/Remote/InProcRemostHostClient.cs +++ b/src/Workspaces/CoreTestUtilities/Remote/InProcRemostHostClient.cs @@ -118,7 +118,7 @@ public event EventHandler? AvailabilityChanged public ValueTask GetPipeAsync(ServiceMoniker serviceMoniker, ServiceActivationOptions options, CancellationToken cancellationToken) => throw ExceptionUtilities.Unreachable(); - public ValueTask GetProxyAsync(ServiceRpcDescriptor descriptor, ServiceActivationOptions options, CancellationToken cancellationToken) where T : class + public async ValueTask GetProxyAsync(ServiceRpcDescriptor descriptor, ServiceActivationOptions options, CancellationToken cancellationToken) where T : class { var pipePair = FullDuplexStream.CreatePipePair(); @@ -145,7 +145,7 @@ public event EventHandler? AvailabilityChanged clientConnection.StartListening(); - return ValueTask.FromResult((T?)clientConnection.ConstructRpcClient()); + return (T?)clientConnection.ConstructRpcClient(); } } diff --git a/src/Workspaces/CoreTestUtilities/Remote/InProcRemoteHostClientProvider.cs b/src/Workspaces/CoreTestUtilities/Remote/InProcRemoteHostClientProvider.cs index cae4c5c4b814c..b893e6e3240c1 100644 --- a/src/Workspaces/CoreTestUtilities/Remote/InProcRemoteHostClientProvider.cs +++ b/src/Workspaces/CoreTestUtilities/Remote/InProcRemoteHostClientProvider.cs @@ -109,8 +109,8 @@ public void Dispose() } } - public Task TryGetRemoteHostClientAsync(CancellationToken cancellationToken) - => Task.FromResult(_lazyClient.Value); + public async Task TryGetRemoteHostClientAsync(CancellationToken cancellationToken) + => _lazyClient.Value; public Task WaitForClientCreationAsync(CancellationToken cancellationToken) => _clientCreationSource.Task.WithCancellation(cancellationToken); diff --git a/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesFiles.cs b/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesFiles.cs index 61a2882c96efa..c139e61f22a2b 100644 --- a/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesFiles.cs +++ b/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesFiles.cs @@ -27,14 +27,14 @@ public TestDynamicFileInfoProviderThatProducesFiles() event EventHandler IDynamicFileInfoProvider.Updated { add { } remove { } } - public Task GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken) + public async Task GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken) { - return Task.FromResult(new DynamicFileInfo( + return new DynamicFileInfo( filePath + ".fromdynamicfile", SourceCodeKind.Regular, new TestTextLoader(GetDynamicFileText(filePath)), designTimeOnly: false, - new TestDocumentServiceProvider())); + new TestDocumentServiceProvider()); } public static string GetDynamicFileText(string filePath) diff --git a/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesNoFiles.cs b/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesNoFiles.cs index 0c1f47e007511..bfe3732cf5f09 100644 --- a/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesNoFiles.cs +++ b/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesNoFiles.cs @@ -27,8 +27,8 @@ public TestDynamicFileInfoProviderThatProducesNoFiles() event EventHandler IDynamicFileInfoProvider.Updated { add { } remove { } } - public Task GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken) - => SpecializedTasks.Null(); + public async Task GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken) + => null; public Task RemoveDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken) => Task.CompletedTask; diff --git a/src/Workspaces/CoreTestUtilities/TestTextLoader.cs b/src/Workspaces/CoreTestUtilities/TestTextLoader.cs index bab25b699b7fe..90f522f286406 100644 --- a/src/Workspaces/CoreTestUtilities/TestTextLoader.cs +++ b/src/Workspaces/CoreTestUtilities/TestTextLoader.cs @@ -18,6 +18,6 @@ public TestTextLoader(string text = "test", SourceHashAlgorithm checksumAlgorith _textAndVersion = TextAndVersion.Create(SourceText.From(text, encoding: null, checksumAlgorithm), VersionStamp.Create()); } - public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(_textAndVersion); + public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => _textAndVersion; } diff --git a/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs b/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs index 4eee565e43341..632f8eef0814c 100644 --- a/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs +++ b/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs @@ -186,8 +186,8 @@ internal TestDocumentLoader(TestHostDocument hostDocument, string text) internal override string? FilePath => _hostDocument.FilePath; - public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(TextAndVersion.Create(SourceText.From(_text, encoding: Encoding.UTF8, options.ChecksumAlgorithm), VersionStamp.Create(), _hostDocument.FilePath)); + public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => TextAndVersion.Create(SourceText.From(_text, encoding: Encoding.UTF8, options.ChecksumAlgorithm), VersionStamp.Create(), _hostDocument.FilePath); } public TextLoader Loader => _loader; diff --git a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs index 308073548de5d..6b52acce18858 100644 --- a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs +++ b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs @@ -468,14 +468,13 @@ internal override void SetDocumentContext(DocumentId documentId) /// Overriding base impl so that when we close a document it goes back to the initial state when the test /// workspace was loaded, throwing away any changes made to the open version. /// - internal override ValueTask TryOnDocumentClosedAsync(DocumentId documentId, CancellationToken cancellationToken) + internal override async ValueTask TryOnDocumentClosedAsync(DocumentId documentId, CancellationToken cancellationToken) { var testDocument = this.GetTestDocument(documentId); Contract.ThrowIfNull(testDocument); Contract.ThrowIfTrue(testDocument.IsSourceGenerated); this.OnDocumentClosedEx(documentId, testDocument.Loader, requireDocumentPresentAndOpen: false); - return ValueTask.CompletedTask; } public override void CloseDocument(DocumentId documentId) diff --git a/src/Workspaces/MSBuild/BuildHost/BuildHost.cs b/src/Workspaces/MSBuild/BuildHost/BuildHost.cs index ec31e8096e6b8..2daff24db28a3 100644 --- a/src/Workspaces/MSBuild/BuildHost/BuildHost.cs +++ b/src/Workspaces/MSBuild/BuildHost/BuildHost.cs @@ -238,12 +238,10 @@ private int LoadProjectCore(string projectFilePath, string projectContent, strin return _buildManager.TryGetOutputFilePathAsync(projectFilePath, cancellationToken); } - public Task ShutdownAsync() + public async Task ShutdownAsync() { _buildManager?.EndBatchBuild(); _server.Shutdown(); - - return Task.CompletedTask; } } diff --git a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs index 4f92c9fea189b..f6239c516b3f1 100644 --- a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs +++ b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs @@ -264,7 +264,7 @@ private async Task> LoadProjectInfosFromPathAsync( return results; } - private Task CreateProjectInfoAsync(ProjectFileInfo projectFileInfo, ProjectId projectId, bool addDiscriminator, CancellationToken cancellationToken) + private async Task CreateProjectInfoAsync(ProjectFileInfo projectFileInfo, ProjectId projectId, bool addDiscriminator, CancellationToken cancellationToken) { var language = projectFileInfo.Language; var projectPath = projectFileInfo.FilePath; @@ -287,8 +287,7 @@ private Task CreateProjectInfoAsync(ProjectFileInfo projectFileInfo var compilationOptions = GetLanguageService(language) ?.GetDefaultCompilationOptions(); - return Task.FromResult( - ProjectInfo.Create( + return ProjectInfo.Create( new ProjectInfo.ProjectAttributes( projectId, version, @@ -301,10 +300,10 @@ private Task CreateProjectInfoAsync(ProjectFileInfo projectFileInfo outputRefFilePath: projectFileInfo.OutputRefFilePath, filePath: projectPath), compilationOptions: compilationOptions, - parseOptions: parseOptions)); + parseOptions: parseOptions); } - return DoOperationAndReportProgressAsync(ProjectLoadOperation.Resolve, projectPath, projectFileInfo.TargetFramework, async () => + return await DoOperationAndReportProgressAsync(ProjectLoadOperation.Resolve, projectPath, projectFileInfo.TargetFramework, async () => { var projectDirectory = Path.GetDirectoryName(projectPath); @@ -381,7 +380,7 @@ private Task CreateProjectInfoAsync(ProjectFileInfo projectFileInfo hostObjectType: null) .WithDefaultNamespace(projectFileInfo.DefaultNamespace) .WithAnalyzerConfigDocuments(analyzerConfigDocuments); - }); + }).ConfigureAwait(false); } private static string GetAssemblyNameFromProjectPath(string? projectFilePath) diff --git a/src/Workspaces/MSBuild/Test/RpcTests.cs b/src/Workspaces/MSBuild/Test/RpcTests.cs index a42b14094941b..04ef68a8171ab 100644 --- a/src/Workspaces/MSBuild/Test/RpcTests.cs +++ b/src/Workspaces/MSBuild/Test/RpcTests.cs @@ -235,12 +235,12 @@ public async Task RequestThatClosesServerDoesNotThrow() private sealed class ObjectWithVoidMethod { public string? Message; public void SetMessage(string message) { Message = message; } } private sealed class ObjectWithAsyncHelloMethods { - public Task HelloAsync(string name) { return Task.FromResult("Hello " + name); } - public Task HelloWithCancellationAsync(string name, CancellationToken cancellationToken) + public async Task HelloAsync(string name) { return "Hello " + name; } + public async Task HelloWithCancellationAsync(string name, CancellationToken cancellationToken) { // We never expect to be given a cancellable cancellation token over RPC Assert.False(cancellationToken.CanBeCanceled); - return Task.FromResult("Hello " + name); + return "Hello " + name; } } diff --git a/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs b/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs index 8897519edc0b0..df628047d59d6 100644 --- a/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs +++ b/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs @@ -35,12 +35,12 @@ private sealed class PdbMatchingSourceTextProvider : IPdbMatchingSourceTextProvi public static readonly PdbMatchingSourceTextProvider Instance = new(); // Returning null will check the file on disk: - public ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) - => ValueTask.FromResult(null); + public async ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) + => null; } private static readonly ActiveStatementSpanProvider s_emptyActiveStatementProvider = - (_, _, _) => ValueTask.FromResult(ImmutableArray.Empty); + async (_, _, _) => ImmutableArray.Empty; private readonly ManagedHotReloadServiceProxy _debuggerService = new(serviceBrokerProvider.ServiceBroker); private readonly SolutionSnapshotProviderProxy _solutionSnapshotProvider = new(serviceBrokerProvider.ServiceBroker); @@ -99,11 +99,11 @@ public async ValueTask StartSessionAsync(CancellationToken cancellationToken) } } - private ValueTask BreakStateOrCapabilitiesChangedAsync(bool? inBreakState, CancellationToken cancellationToken) + private async ValueTask BreakStateOrCapabilitiesChangedAsync(bool? inBreakState, CancellationToken cancellationToken) { if (_disabled) { - return ValueTask.CompletedTask; + return; } try @@ -115,8 +115,6 @@ private ValueTask BreakStateOrCapabilitiesChangedAsync(bool? inBreakState, Cance { Disable(); } - - return ValueTask.CompletedTask; } public ValueTask EnterBreakStateAsync(CancellationToken cancellationToken) @@ -128,11 +126,11 @@ public ValueTask ExitBreakStateAsync(CancellationToken cancellationToken) public ValueTask OnCapabilitiesChangedAsync(CancellationToken cancellationToken) => BreakStateOrCapabilitiesChangedAsync(inBreakState: null, cancellationToken); - public ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) + public async ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { - return ValueTask.CompletedTask; + return; } try @@ -149,19 +147,17 @@ public ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) { Disable(); } - - return ValueTask.CompletedTask; } [Obsolete] public ValueTask UpdateBaselinesAsync(ImmutableArray projectPaths, CancellationToken cancellationToken) => throw new NotImplementedException(); - public ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) + public async ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { - return ValueTask.CompletedTask; + return; } try @@ -175,15 +171,13 @@ public ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) { Disable(); } - - return ValueTask.CompletedTask; } - public ValueTask EndSessionAsync(CancellationToken cancellationToken) + public async ValueTask EndSessionAsync(CancellationToken cancellationToken) { if (_disabled) { - return ValueTask.CompletedTask; + return; } try @@ -200,8 +194,6 @@ public ValueTask EndSessionAsync(CancellationToken cancellationToken) { Disable(); } - - return ValueTask.CompletedTask; } /// diff --git a/src/Workspaces/Remote/ServiceHub/Host/RemoteDocumentDifferenceService.cs b/src/Workspaces/Remote/ServiceHub/Host/RemoteDocumentDifferenceService.cs index 934c7a12b76fb..aaef097cfe118 100644 --- a/src/Workspaces/Remote/ServiceHub/Host/RemoteDocumentDifferenceService.cs +++ b/src/Workspaces/Remote/ServiceHub/Host/RemoteDocumentDifferenceService.cs @@ -33,8 +33,8 @@ internal sealed class CSharpDocumentDifferenceService() : RemoteDocumentDifferen [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class VisualBasicDocumentDifferenceService() : RemoteDocumentDifferenceService; - public Task GetChangedMemberAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) + public async Task GetChangedMemberAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { - return SpecializedTasks.Null(); + return null; } } diff --git a/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs b/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs index f6603fc983db9..2fd6afe32773e 100644 --- a/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs +++ b/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs @@ -58,7 +58,7 @@ await RunWithSolutionAsync( assetProvider, solutionChecksum, updatePrimaryBranch: true, - implementation: static _ => ValueTask.FromResult(false), + implementation: static async _ => false, cancellationToken).ConfigureAwait(false); } @@ -340,7 +340,7 @@ public async ValueTask GetSolutionAsync( CancellationToken cancellationToken) { var (solution, _) = await _remoteWorkspace.RunWithSolutionAsync( - assetProvider, solutionChecksum, updatePrimaryBranch, _ => ValueTask.FromResult(false), cancellationToken).ConfigureAwait(false); + assetProvider, solutionChecksum, updatePrimaryBranch, async _ => false, cancellationToken).ConfigureAwait(false); return solution; } } diff --git a/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.cs b/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.cs index 48bcac81ede3e..2625afbdbd48c 100644 --- a/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.cs +++ b/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.cs @@ -94,7 +94,7 @@ public async ValueTask GetSolutionAsync(ServiceBrokerClient client, Ch var (solution, _) = await workspace.RunWithSolutionAsync( assetProvider, solutionChecksum, - static _ => ValueTask.FromResult(false), + static async _ => false, cancellationToken).ConfigureAwait(false); return solution; diff --git a/src/Workspaces/Remote/ServiceHub/Services/AssetSynchronization/RemoteAssetSynchronizationService.cs b/src/Workspaces/Remote/ServiceHub/Services/AssetSynchronization/RemoteAssetSynchronizationService.cs index d96419e82b0d3..26bf388a88ef1 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/AssetSynchronization/RemoteAssetSynchronizationService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/AssetSynchronization/RemoteAssetSynchronizationService.cs @@ -46,11 +46,10 @@ public ValueTask SynchronizePrimaryWorkspaceAsync(Checksum solutionChecksum, Can }, cancellationToken); } - public ValueTask SynchronizeActiveDocumentAsync(DocumentId? documentId, CancellationToken cancellationToken) + public async ValueTask SynchronizeActiveDocumentAsync(DocumentId? documentId, CancellationToken cancellationToken) { var documentTrackingService = GetWorkspace().Services.GetRequiredService() as RemoteDocumentTrackingService; documentTrackingService?.SetActiveDocument(documentId); - return ValueTask.CompletedTask; } public ValueTask SynchronizeTextChangesAsync( diff --git a/src/Workspaces/Remote/ServiceHub/Services/AsynchronousOperationListener/RemoteAsynchronousOperationListenerService.cs b/src/Workspaces/Remote/ServiceHub/Services/AsynchronousOperationListener/RemoteAsynchronousOperationListenerService.cs index e58ac47a6bb35..c292ddb17447e 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/AsynchronousOperationListener/RemoteAsynchronousOperationListenerService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/AsynchronousOperationListener/RemoteAsynchronousOperationListenerService.cs @@ -25,22 +25,21 @@ public RemoteAsynchronousOperationListenerService(in ServiceConstructionArgument public ValueTask EnableAsync(bool enable, bool diagnostics, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { AsynchronousOperationListenerProvider.Enable(enable, diagnostics); - return default; }, cancellationToken); } public ValueTask IsCompletedAsync(ImmutableArray featureNames, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { var workspace = GetWorkspace(); var exportProvider = workspace.Services.SolutionServices.ExportProvider; var listenerProvider = exportProvider.GetExports().Single().Value; - return new ValueTask(!listenerProvider.HasPendingWaiter([.. featureNames])); + return !listenerProvider.HasPendingWaiter([.. featureNames]); }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/BrokeredServiceBase.FactoryBase.cs b/src/Workspaces/Remote/ServiceHub/Services/BrokeredServiceBase.FactoryBase.cs index a79cd330b7dd1..2f810a4115815 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/BrokeredServiceBase.FactoryBase.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/BrokeredServiceBase.FactoryBase.cs @@ -44,7 +44,7 @@ protected virtual TService CreateService( object? clientRpcTarget) => CreateService(arguments); - public Task CreateAsync( + public async Task CreateAsync( Stream stream, IServiceProvider hostProvidedServices, ServiceActivationOptions serviceActivationOptions, @@ -67,11 +67,11 @@ public Task CreateAsync( CultureInfo.DefaultThreadCurrentCulture = serviceActivationOptions.ClientCulture; } - return Task.FromResult((object)Create( + return (object)Create( stream.UsePipe(), hostProvidedServices, serviceActivationOptions, - serviceBroker)); + serviceBroker); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { diff --git a/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs b/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs index f7a9c14a22483..c36ad6e040758 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs @@ -121,7 +121,7 @@ public ValueTask> GetSourceGeneratorDiagnosticsAs public ValueTask ReportAnalyzerPerformanceAsync(ImmutableArray snapshot, int unitCount, bool forSpanAnalysis, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { using (RoslynLogger.LogBlock(FunctionId.CodeAnalysisService_ReportAnalyzerPerformance, cancellationToken)) { @@ -130,13 +130,11 @@ public ValueTask ReportAnalyzerPerformanceAsync(ImmutableArray(); if (service == null) { - return default; + return; } service.AddSnapshot(snapshot, unitCount, forSpanAnalysis); } - - return default; }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs b/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs index a76ae37045002..0900f79dc119d 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs @@ -82,13 +82,13 @@ private ActiveStatementSpanProvider CreateActiveStatementSpanProvider(RemoteServ /// public ValueTask StartDebuggingSessionAsync(Checksum solutionChecksum, RemoteServiceCallbackId callbackId, bool reportDiagnostics, CancellationToken cancellationToken) { - return RunServiceAsync(solutionChecksum, solution => + return RunServiceAsync(solutionChecksum, async solution => { var debuggerService = new ManagedEditAndContinueDebuggerService(_callback, callbackId); var sourceTextProvider = new SourceTextProvider(_callback, callbackId); var sessionId = GetService().StartDebuggingSession(solution, debuggerService, sourceTextProvider, reportDiagnostics); - return ValueTask.FromResult(sessionId); + return sessionId; }, cancellationToken); } @@ -97,10 +97,9 @@ public ValueTask StartDebuggingSessionAsync(Checksum solutio /// public ValueTask BreakStateOrCapabilitiesChangedAsync(DebuggingSessionId sessionId, bool? inBreakState, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { GetService().BreakStateOrCapabilitiesChanged(sessionId, inBreakState); - return ValueTask.CompletedTask; }, cancellationToken); } @@ -109,10 +108,9 @@ public ValueTask BreakStateOrCapabilitiesChangedAsync(DebuggingSessionId session /// public ValueTask EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { GetService().EndDebuggingSession(sessionId); - return ValueTask.CompletedTask; }, cancellationToken); } @@ -163,10 +161,9 @@ public ValueTask> GetDocumentDiagnosticsAsync(Che /// public ValueTask CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { GetService().CommitSolutionUpdate(sessionId); - return ValueTask.CompletedTask; }, cancellationToken); } @@ -175,10 +172,9 @@ public ValueTask CommitSolutionUpdateAsync(DebuggingSessionId sessionId, Cancell /// public ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { GetService().DiscardSolutionUpdate(sessionId); - return default; }, cancellationToken); } @@ -210,10 +206,9 @@ public ValueTask> GetAdjustedActiveStatement /// public ValueTask SetFileLoggingDirectoryAsync(string? logDirectory, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { GetService().SetFileLoggingDirectory(logDirectory); - return default; }, cancellationToken); } } diff --git a/src/Workspaces/Remote/ServiceHub/Services/ExtensionMethodImportCompletion/RemoteExtensionMethodImportCompletionService.cs b/src/Workspaces/Remote/ServiceHub/Services/ExtensionMethodImportCompletion/RemoteExtensionMethodImportCompletionService.cs index 679501bc4974c..8e0bf1dd7cafd 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/ExtensionMethodImportCompletion/RemoteExtensionMethodImportCompletionService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/ExtensionMethodImportCompletion/RemoteExtensionMethodImportCompletionService.cs @@ -61,11 +61,10 @@ public ValueTask> GetUnimported public ValueTask WarmUpCacheAsync(Checksum solutionChecksum, ProjectId projectId, CancellationToken cancellationToken) { - return RunServiceAsync(solutionChecksum, solution => + return RunServiceAsync(solutionChecksum, async solution => { var project = solution.GetRequiredProject(projectId); ExtensionMemberImportCompletionHelper.WarmUpCacheInCurrentProcess(project); - return ValueTask.CompletedTask; }, cancellationToken); } } diff --git a/src/Workspaces/Remote/ServiceHub/Services/Initialization/RemoteInitializationService.cs b/src/Workspaces/Remote/ServiceHub/Services/Initialization/RemoteInitializationService.cs index f1be8f34cafab..07e859ba90e8e 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/Initialization/RemoteInitializationService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/Initialization/RemoteInitializationService.cs @@ -28,12 +28,12 @@ protected override IRemoteInitializationService CreateService(in ServiceConstruc try { - var processId = await RunServiceAsync(cancellationToken => + var processId = await RunServiceAsync(async cancellationToken => { var service = (RemoteWorkspaceConfigurationService)GetWorkspaceServices().GetRequiredService(); service.InitializeOptions(options); - return ValueTask.FromResult(Process.GetCurrentProcess().Id); + return Process.GetCurrentProcess().Id; }, cancellationToken).ConfigureAwait(false); return (processId, errorMessage); diff --git a/src/Workspaces/Remote/ServiceHub/Services/LegacySolutionEvents/RemoteLegacySolutionEventsAggregationService.cs b/src/Workspaces/Remote/ServiceHub/Services/LegacySolutionEvents/RemoteLegacySolutionEventsAggregationService.cs index 320060bf361a2..7d4739b255a24 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/LegacySolutionEvents/RemoteLegacySolutionEventsAggregationService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/LegacySolutionEvents/RemoteLegacySolutionEventsAggregationService.cs @@ -24,11 +24,11 @@ public RemoteLegacySolutionEventsAggregationService(in ServiceConstructionArgume public ValueTask ShouldReportChangesAsync(CancellationToken cancellationToken) { return RunServiceImplAsync( - cancellationToken => + async cancellationToken => { var services = this.GetWorkspaceServices(); var aggregationService = services.GetRequiredService(); - return new ValueTask(aggregationService.ShouldReportChanges(services)); + return aggregationService.ShouldReportChanges(services); }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.PerformanceReporter.cs b/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.PerformanceReporter.cs index 3f4230e85e358..0d5a5c15b9248 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.PerformanceReporter.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.PerformanceReporter.cs @@ -43,10 +43,10 @@ public PerformanceReporter( _diagnosticAnalyzerPerformanceTracker.SnapshotAdded += (_, _) => _workQueue.AddWork(); } - private ValueTask ProcessWorkAsync(CancellationToken cancellationToken) + private async ValueTask ProcessWorkAsync(CancellationToken cancellationToken) { if (!_telemetrySession.IsOptedIn) - return ValueTask.CompletedTask; + return; using (RoslynLogger.LogBlock(FunctionId.Diagnostics_GeneratePerformaceReport, cancellationToken)) { @@ -70,8 +70,6 @@ private ValueTask ProcessWorkAsync(CancellationToken cancellationToken) } } } - - return ValueTask.CompletedTask; } } } diff --git a/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.cs b/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.cs index bb9112646ca6e..ab9572daa9c4c 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.cs @@ -39,7 +39,7 @@ protected override IRemoteProcessTelemetryService CreateService(in ServiceConstr /// public ValueTask InitializeTelemetrySessionAsync(int hostProcessId, string serializedSession, bool logDelta, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { var services = GetWorkspace().Services; @@ -65,8 +65,6 @@ public ValueTask InitializeTelemetrySessionAsync(int hostProcessId, string seria // We know in the remote layer that this type must exist. _performanceReporter = new PerformanceReporter(telemetrySession, diagnosticAnalyzerPerformanceTracker, _shutdownCancellationSource.Token); } - - return ValueTask.CompletedTask; }, cancellationToken); } @@ -75,7 +73,7 @@ public ValueTask InitializeTelemetrySessionAsync(int hostProcessId, string seria /// public ValueTask EnableLoggingAsync(ImmutableArray loggerTypeNames, ImmutableArray functionIds, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { var functionIdsSet = new HashSet(functionIds); bool logChecker(FunctionId id) => functionIdsSet.Contains(id); @@ -83,8 +81,6 @@ public ValueTask EnableLoggingAsync(ImmutableArray loggerTypeNames, Immu // we only support 2 types of loggers SetRoslynLogger(loggerTypeNames, () => new EtwLogger(logChecker)); SetRoslynLogger(loggerTypeNames, () => new TraceLogger(logChecker)); - - return ValueTask.CompletedTask; }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs b/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs index 84ea91adddd5d..96506aa72e8a1 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs @@ -93,13 +93,13 @@ public ValueTask CompileQueryAsync( string referenceAssembliesDir, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { var services = GetWorkspaceServices(); var service = GetRequiredService(); var result = service.CompileQuery(services, query, targetLanguage, referenceAssembliesDir, TraceLogger, cancellationToken); - return ValueTask.FromResult(result); + return result; }, cancellationToken); } @@ -108,12 +108,10 @@ public ValueTask CompileQueryAsync( /// public ValueTask DiscardQueryAsync(CompiledQueryId queryId, CancellationToken cancellationToken) { - return RunServiceAsync(cancellationToken => + return RunServiceAsync(async cancellationToken => { var service = GetRequiredService(); service.DiscardQuery(queryId); - - return default; }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/SourceGeneration/RemoteSourceGenerationService.cs b/src/Workspaces/Remote/ServiceHub/Services/SourceGeneration/RemoteSourceGenerationService.cs index ecc5845487b8e..2a48e1386c70f 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/SourceGeneration/RemoteSourceGenerationService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/SourceGeneration/RemoteSourceGenerationService.cs @@ -153,13 +153,13 @@ public ValueTask> GetSourceGeneratorIden string analyzerReferenceFullPath, CancellationToken cancellationToken) { - return RunServiceAsync(solutionChecksum, solution => + return RunServiceAsync(solutionChecksum, async solution => { var project = solution.GetRequiredProject(projectId); var analyzerReference = project.AnalyzerReferences .First(r => r.FullPath == analyzerReferenceFullPath); - return ValueTask.FromResult(SourceGeneratorIdentity.GetIdentities(analyzerReference, project.Language)); + return SourceGeneratorIdentity.GetIdentities(analyzerReference, project.Language); }, cancellationToken); } @@ -169,19 +169,19 @@ public ValueTask HasAnalyzersOrSourceGeneratorsAsync( string analyzerReferenceFullPath, CancellationToken cancellationToken) { - return RunServiceAsync(solutionChecksum, solution => + return RunServiceAsync(solutionChecksum, async solution => { var project = solution.GetRequiredProject(projectId); var analyzerReference = project.AnalyzerReferences .First(r => r.FullPath == analyzerReferenceFullPath); - return ValueTask.FromResult(analyzerReference.HasAnalyzersOrSourceGenerators(project.Language)); + return analyzerReference.HasAnalyzersOrSourceGenerators(project.Language); }, cancellationToken); } - public ValueTask>> FetchAndClearTelemetryKeyValuePairsAsync(CancellationToken _) + public async ValueTask>> FetchAndClearTelemetryKeyValuePairsAsync(CancellationToken _) { var workspaceService = GetWorkspaceServices().GetRequiredService(); - return ValueTask.FromResult(workspaceService.FetchKeysAndAndClear()); + return workspaceService.FetchKeysAndAndClear(); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy.cs index 43cfec9304f24..47c2acd96f004 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy.cs @@ -21,7 +21,7 @@ public static AsyncLazy Create(Func public static AsyncLazy Create(Func synchronousComputeFunction, TArg arg) => Create( - asynchronousComputeFunction: static (outerArg, cancellationToken) => Task.FromResult(outerArg.synchronousComputeFunction(outerArg.arg, cancellationToken)), + asynchronousComputeFunction: static async (outerArg, cancellationToken) => outerArg.synchronousComputeFunction(outerArg.arg, cancellationToken), synchronousComputeFunction: static (outerArg, cancellationToken) => outerArg.synchronousComputeFunction(outerArg.arg, cancellationToken), (synchronousComputeFunction, arg)); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs index 895e26313b279..01e5f7a2833ff 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs @@ -182,17 +182,16 @@ public void Dispose() instanceToDispose?.Dispose(); } - public ValueTask DisposeAsync() + public async ValueTask DisposeAsync() { var instanceToDispose = DisposeImpl(); if (instanceToDispose == null) - return ValueTask.CompletedTask; + return; if (instanceToDispose is IAsyncDisposable asyncDisposable) - return asyncDisposable.DisposeAsync(); + await asyncDisposable.DisposeAsync().ConfigureAwait(false); instanceToDispose.Dispose(); - return ValueTask.CompletedTask; } private T? DisposeImpl() diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Editing/CSharpImportAdder.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Editing/CSharpImportAdder.cs index f612474882770..424ec08eda861 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Editing/CSharpImportAdder.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Editing/CSharpImportAdder.cs @@ -133,7 +133,7 @@ public async Task AddPotentiallyConflictingImportsAsync(SyntaxNode container, Ha await ProducerConsumer.RunParallelAsync( source: nodes, - produceItems: static (node, onItemsFound, args, cancellationToken) => + produceItems: static async (node, onItemsFound, args, cancellationToken) => { var (self, containsAnonymousMethods, _) = args; if (node is SimpleNameSyntax nameSyntaxNode) @@ -142,8 +142,6 @@ await ProducerConsumer.RunParallelAsync( self.ProduceConflicts(memberAccessExpressionNode, containsAnonymousMethods, onItemsFound, cancellationToken); else throw ExceptionUtilities.Unreachable(); - - return Task.CompletedTask; }, consumeItems: static async (items, args, cancellationToken) => { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/ForkingSyntaxEditorBasedCodeFixProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/ForkingSyntaxEditorBasedCodeFixProvider.cs index e8b6f1d6bbe88..f334a07d3e652 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/ForkingSyntaxEditorBasedCodeFixProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/ForkingSyntaxEditorBasedCodeFixProvider.cs @@ -45,11 +45,10 @@ protected sealed override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnost // Never try to fix the secondary diagnostics that were produced just to fade out code. => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); - public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var (title, equivalenceKey) = GetTitleAndEquivalenceKey(context); RegisterCodeFix(context, title, equivalenceKey); - return Task.CompletedTask; } protected sealed override async Task FixAllAsync( diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/MultiProjectSafeFixAllProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/MultiProjectSafeFixAllProvider.cs index 80d4f64262154..c16a605f8bf08 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/MultiProjectSafeFixAllProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/MultiProjectSafeFixAllProvider.cs @@ -44,7 +44,7 @@ internal abstract class MultiProjectSafeFixAllProvider : FixAllProvider return CodeAction.Create( fixAllContext.GetDefaultFixAllTitle(), - (_, _) => Task.FromResult(updatedSolution), + async (_, _) => updatedSolution, equivalenceKey: null, CodeActionPriority.Default #if WORKSPACE diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs index 40f6a6abce8d6..f388d23ca2a00 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs @@ -12,12 +12,12 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions; internal static partial class TextDocumentExtensions { #if !WORKSPACE - public static ValueTask GetValueTextAsync(this TextDocument document, CancellationToken cancellationToken) + public static async ValueTask GetValueTextAsync(this TextDocument document, CancellationToken cancellationToken) { if (document.TryGetText(out var text)) - return ValueTask.FromResult(text); + return text; - return new ValueTask(document.GetTextAsync(cancellationToken)); + return await document.GetTextAsync(cancellationToken).ConfigureAwait(false); } #endif diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Options/OptionsProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Options/OptionsProvider.cs index acf7fef59183e..79192aaf593cb 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Options/OptionsProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Options/OptionsProvider.cs @@ -20,8 +20,8 @@ internal static class OptionsProvider { private sealed class OptionsReaderProvider(IOptionsReader optionsReader, Func reader) : OptionsProvider { - public ValueTask GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTask.FromResult(reader(optionsReader, languageServices.Language)); + public async ValueTask GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) + => reader(optionsReader, languageServices.Language); } public static OptionsProvider GetProvider(this IOptionsReader optionsReader, Func reader) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SymbolFinder/SymbolFinderInternal.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SymbolFinder/SymbolFinderInternal.cs index c6cee45a9fc67..4312b86087ff0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SymbolFinder/SymbolFinderInternal.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SymbolFinder/SymbolFinderInternal.cs @@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.FindSymbols; internal static class SymbolFinderInternal { /// - internal static ValueTask FindSourceDefinitionAsync( + internal static async ValueTask FindSourceDefinitionAsync( ISymbol? symbol, Solution solution, CancellationToken cancellationToken) { if (symbol != null) @@ -32,11 +32,11 @@ internal static class SymbolFinderInternal case SymbolKind.Property: case SymbolKind.TypeParameter: case SymbolKind.Namespace: - return FindSourceDefinitionWorkerAsync(symbol, solution, cancellationToken); + return await FindSourceDefinitionWorkerAsync(symbol, solution, cancellationToken).ConfigureAwait(false); } } - return new ValueTask(result: null); + return null; } private static async ValueTask FindSourceDefinitionWorkerAsync( diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/AsyncSymbolVisitor`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/AsyncSymbolVisitor`1.cs index cc5811efb3aa5..fbe93246ae201 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/AsyncSymbolVisitor`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/AsyncSymbolVisitor`1.cs @@ -14,6 +14,6 @@ internal abstract class AsyncSymbolVisitor : SymbolVisitor Visit(ISymbol? symbol) => symbol?.Accept(this) ?? ValueTask.FromResult(DefaultResult); - public override ValueTask DefaultVisit(ISymbol symbol) - => ValueTask.FromResult(DefaultResult); + public override async ValueTask DefaultVisit(ISymbol symbol) + => DefaultResult; } diff --git a/src/Workspaces/TestAnalyzerReference/NonSourceFileRefactoring.cs b/src/Workspaces/TestAnalyzerReference/NonSourceFileRefactoring.cs index d2b9df631ad53..59cabddbb16ce 100644 --- a/src/Workspaces/TestAnalyzerReference/NonSourceFileRefactoring.cs +++ b/src/Workspaces/TestAnalyzerReference/NonSourceFileRefactoring.cs @@ -18,7 +18,7 @@ namespace Microsoft.CodeAnalysis.CodeRefactorings; [Shared] public sealed class NonSourceFileRefactoring : CodeRefactoringProvider { - public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(CodeAction.Create(nameof(NonSourceFileRefactoring), createChangedSolution: async ct => @@ -30,8 +30,6 @@ public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) return document.Project.Solution.WithAdditionalDocumentText(document.Id, newText); return document.Project.Solution.WithAnalyzerConfigDocumentText(document.Id, newText); })); - - return Task.CompletedTask; } }