Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docfx/analyzers/VSTHRD003.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,43 @@ When required to await a task that was started earlier, start it within a delega
`JoinableTaskFactory.RunAsync`, storing the resulting `JoinableTask` in a field or variable.
You can safely await the `JoinableTask` later.

## Suppressing warnings for completed tasks

If you have a property, method, or field that returns a pre-completed task (such as a cached task with a known value),
you can suppress this warning by applying the `[CompletedTask]` attribute to the member.
This attribute is automatically included when you install the `Microsoft.VisualStudio.Threading.Analyzers` package.
Comment on lines +15 to +17
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot what if the attribute could be applied at the assembly level, such that you could also apply this attribute to types you don't control. For example if I was using TplExtensions and it wasn't annotated:

[assembly: CompletedTask(Member = "System.Threading.TplExtensions.TrueTask")]

Or something like that. If this isn't feasible, or has major drawbacks, feel free to push back.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea! I've implemented assembly-level attribute support. You can now mark external members like this:

[assembly: CompletedTask(Member = "ExternalLibrary.ExternalClass.CompletedTaskProperty")]

The attribute now supports a Member property that accepts fully qualified names in the format Namespace.TypeName.MemberName. The analyzer checks assembly-level attributes and matches them against the symbols being analyzed. Multiple assembly-level attributes are supported for marking different external members.

Committed in d067b66.


```csharp
[Microsoft.VisualStudio.Threading.CompletedTask]
private static readonly Task<bool> TrueTask = Task.FromResult(true);

async Task MyMethodAsync()
{
await TrueTask; // No warning - TrueTask is marked as a completed task
}
```

### Marking external types

You can also apply the attribute at the assembly level to mark members in external types that you don't control:

```csharp
[assembly: Microsoft.VisualStudio.Threading.CompletedTask(Member = "ExternalLibrary.ExternalClass.CompletedTaskProperty")]
```

This is useful when you're using third-party libraries that have pre-completed tasks but aren't annotated with the attribute.
The `Member` property should contain the fully qualified name of the member in the format `Namespace.TypeName.MemberName`.

The analyzer already recognizes the following as safe to await without the attribute:
- `Task.CompletedTask`
- `Task.FromResult(...)`
- `Task.FromCanceled(...)`
- `Task.FromException(...)`
- `TplExtensions.CompletedTask`
- `TplExtensions.CanceledTask`
- `TplExtensions.TrueTask`
- `TplExtensions.FalseTask`

## Simple examples of patterns that are flagged by this analyzer

The following example would likely deadlock if `MyMethod` were called on the main thread,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,42 @@ public override void Initialize(AnalysisContext context)
context.RegisterSyntaxNodeAction(Utils.DebuggableWrapper(this.AnalyzeLambdaExpression), SyntaxKind.ParenthesizedLambdaExpression);
}

private static bool IsSymbolAlwaysOkToAwait(ISymbol? symbol)
private static bool IsSymbolAlwaysOkToAwait(ISymbol? symbol, Compilation compilation)
{
if (symbol is null)
{
return false;
}

// Check if the symbol has the CompletedTaskAttribute directly applied
if (symbol.GetAttributes().Any(attr =>
attr.AttributeClass?.Name == Types.CompletedTaskAttribute.TypeName &&
attr.AttributeClass.BelongsToNamespace(Types.CompletedTaskAttribute.Namespace)))
{
return true;
}

// Check for assembly-level CompletedTaskAttribute
foreach (AttributeData assemblyAttr in compilation.Assembly.GetAttributes())
{
if (assemblyAttr.AttributeClass?.Name == Types.CompletedTaskAttribute.TypeName &&
assemblyAttr.AttributeClass.BelongsToNamespace(Types.CompletedTaskAttribute.Namespace))
{
// Look for the Member named argument
foreach (KeyValuePair<string, TypedConstant> namedArg in assemblyAttr.NamedArguments)
{
if (namedArg.Key == "Member" && namedArg.Value.Value is string memberName)
{
// Check if this symbol matches the specified member name
if (IsSymbolMatchingMemberName(symbol, memberName))
{
return true;
}
}
}
}
}

if (symbol is IFieldSymbol field)
{
// Allow the TplExtensions.CompletedTask and related fields.
Expand All @@ -95,6 +129,45 @@ private static bool IsSymbolAlwaysOkToAwait(ISymbol? symbol)
return false;
}

private static bool IsSymbolMatchingMemberName(ISymbol symbol, string memberName)
{
// Build the fully qualified name of the symbol
string fullyQualifiedName = GetFullyQualifiedName(symbol);

// Compare with the member name (case-sensitive)
return string.Equals(fullyQualifiedName, memberName, StringComparison.Ordinal);
}

private static string GetFullyQualifiedName(ISymbol symbol)
{
if (symbol.ContainingType is null)
{
return symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
}

// For members (properties, fields, methods), construct: Namespace.TypeName.MemberName
List<string> parts = new List<string>();

// Add member name
parts.Add(symbol.Name);

// Add containing type hierarchy
INamedTypeSymbol? currentType = symbol.ContainingType;
while (currentType is not null)
{
parts.Insert(0, currentType.Name);
currentType = currentType.ContainingType;
}

// Add namespace
if (symbol.ContainingNamespace is not null && !symbol.ContainingNamespace.IsGlobalNamespace)
{
parts.Insert(0, symbol.ContainingNamespace.ToDisplayString());
}

return string.Join(".", parts);
}

private void AnalyzeArrowExpressionClause(SyntaxNodeAnalysisContext context)
{
var arrowExpressionClause = (ArrowExpressionClauseSyntax)context.Node;
Expand Down Expand Up @@ -183,7 +256,7 @@ private void AnalyzeAwaitExpression(SyntaxNodeAnalysisContext context)
symbolType = localSymbol.Type;
dataflowAnalysisCompatibleVariable = true;
break;
case IPropertySymbol propertySymbol when !IsSymbolAlwaysOkToAwait(propertySymbol):
case IPropertySymbol propertySymbol when !IsSymbolAlwaysOkToAwait(propertySymbol, context.Compilation):
symbolType = propertySymbol.Type;

if (focusedExpression is MemberAccessExpressionSyntax memberAccessExpression)
Expand Down Expand Up @@ -277,7 +350,7 @@ private void AnalyzeAwaitExpression(SyntaxNodeAnalysisContext context)
}

ISymbol? definition = declarationSemanticModel.GetSymbolInfo(memberAccessSyntax, cancellationToken).Symbol;
if (IsSymbolAlwaysOkToAwait(definition))
if (IsSymbolAlwaysOkToAwait(definition, context.Compilation))
{
return null;
}
Expand All @@ -288,6 +361,12 @@ private void AnalyzeAwaitExpression(SyntaxNodeAnalysisContext context)

break;
case IMethodSymbol methodSymbol:
// Check if the method itself has the CompletedTaskAttribute
if (IsSymbolAlwaysOkToAwait(methodSymbol, context.Compilation))
{
return null;
}

if (Utils.IsTask(methodSymbol.ReturnType) && focusedExpression is InvocationExpressionSyntax invocationExpressionSyntax)
{
// Consider all arguments
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if !COMPLETEDTASKATTRIBUTE_INCLUDED
#define COMPLETEDTASKATTRIBUTE_INCLUDED

namespace Microsoft.VisualStudio.Threading;

/// <summary>
/// Indicates that a property, method, or field returns a task that is already completed.
/// This suppresses VSTHRD003 warnings when awaiting the returned task.
/// </summary>
/// <remarks>
/// <para>
/// Apply this attribute to properties, methods, or fields that return cached, pre-completed tasks
/// such as singleton instances with well-known immutable values.
/// The VSTHRD003 analyzer will not report warnings when these members are awaited,
/// as awaiting an already-completed task does not pose a risk of deadlock.
/// </para>
/// <para>
/// This attribute can also be applied at the assembly level to mark members in external types
/// that you don't control:
/// <code>
/// [assembly: CompletedTask(Member = "System.Threading.Tasks.TplExtensions.TrueTask")]
/// </code>
/// </para>
/// </remarks>
[System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method | System.AttributeTargets.Field | System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
#pragma warning disable SA1649 // File name should match first type name
internal sealed class CompletedTaskAttribute : System.Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="CompletedTaskAttribute"/> class.
/// </summary>
public CompletedTaskAttribute()
{
}

/// <summary>
/// Gets or sets the fully qualified name of the member that returns a completed task.
/// This is only used when the attribute is applied at the assembly level.
/// </summary>
/// <remarks>
/// The format should be: "Namespace.TypeName.MemberName".
/// For example: "System.Threading.Tasks.TplExtensions.TrueTask".
/// </remarks>
public string? Member { get; set; }
}
#pragma warning restore SA1649 // File name should match first type name

#endif
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<AdditionalFiles Include="$(MSBuildThisFileDirectory)AdditionalFiles\**">
<AdditionalFiles Include="$(MSBuildThisFileDirectory)AdditionalFiles\*.txt">
<Visible>false</Visible>
</AdditionalFiles>
<Compile Include="$(MSBuildThisFileDirectory)AdditionalFiles\*.cs" Link="%(Filename)%(Extension)">
<Visible>false</Visible>
</Compile>
</ItemGroup>
</Project>
7 changes: 7 additions & 0 deletions src/Microsoft.VisualStudio.Threading.Analyzers/Types.cs
Original file line number Diff line number Diff line change
Expand Up @@ -246,4 +246,11 @@ public static class TypeLibTypeAttribute

public static readonly ImmutableArray<string> Namespace = Namespaces.SystemRuntimeInteropServices;
}

public static class CompletedTaskAttribute
{
public const string TypeName = "CompletedTaskAttribute";

public static readonly ImmutableArray<string> Namespace = Namespaces.MicrosoftVisualStudioThreading;
}
}
Loading
Loading