Skip to content

Commit

Permalink
Fix VSTHRD004 mis-fire on NoThrowAwaitable()
Browse files Browse the repository at this point in the history
  • Loading branch information
AArnott committed Oct 23, 2023
1 parent a74e8e8 commit 047a498
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,23 @@ private void AnalyzeInvocation(OperationAnalysisContext context)
methodSymbol.ContainingType.Name == Types.JoinableTaskFactory.TypeName &&
methodSymbol.ContainingType.BelongsToNamespace(Types.JoinableTaskFactory.Namespace))
{
// This is a call to JTF.SwitchToMainThreadAsync(). Is it being (directly) awaited?
if (!(invocation.Parent is IAwaitOperation))
// This is a call to JTF.SwitchToMainThreadAsync(). Is it being awaited in some ancestor?
for (IOperation? parentOp = invocation.Parent; parentOp is not null; parentOp = parentOp.Parent)
{
Location? location = (this.LanguageUtils.IsolateMethodName(invocation) ?? invocation.Syntax).GetLocation();
context.ReportDiagnostic(Diagnostic.Create(Descriptor, location));
if (parentOp is IAwaitOperation)
{
return;
}

if (parentOp is IExpressionStatementOperation or IReturnOperation)
{
// We've reached the top of the statement without finding an await.
break;
}
}

Location? location = (this.LanguageUtils.IsolateMethodName(invocation) ?? invocation.Syntax).GetLocation();
context.ReportDiagnostic(Diagnostic.Create(Descriptor, location));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,26 @@ async Task FooAsync()
await CSVerify.VerifyAnalyzerAsync(test);
}

[Fact]
public async Task AsyncMethodWithAwaitNoThrowAwaitable_ProducesNoDiagnostic()
{
var test = @"
using System.Threading.Tasks;
class Test
{
Microsoft.VisualStudio.Threading.JoinableTaskFactory jtf;
async Task FooAsync()
{
await jtf.SwitchToMainThreadAsync().NoThrowAwaitable();
}
}
";

await CSVerify.VerifyAnalyzerAsync(test);
}

[Fact]
public async Task TaskReturningSyncMethod_ProducesDiagnostic()
{
Expand Down

0 comments on commit 047a498

Please sign in to comment.