Skip to content

Instantly share code, notes, and snippets.

@bradwilson
Last active December 15, 2015 11:09
Show Gist options
  • Save bradwilson/5251303 to your computer and use it in GitHub Desktop.
Save bradwilson/5251303 to your computer and use it in GitHub Desktop.
FxCop rule to ensure that Task-returning methods are suffixed with 'Async'
using System.Runtime.CompilerServices;
using Microsoft.FxCop.Sdk;
namespace Tier3.FxCop.TaskRules
{
public class NameTaskReturningMethodAppropriately : BaseIntrospectionRule
{
public NameTaskReturningMethodAppropriately() :
base("NameTaskReturningMethodAppropriately",
"Tier3.FxCop.Rules",
typeof(NameTaskReturningMethodAppropriately).Assembly)
{
}
public override ProblemCollection Check(Member member)
{
var method = member as Method;
if (method != null
&& method.ReturnType.IsTask()
&& !method.Name.Name.EndsWith("Async")
&& !method.HasCustomAttribute(typeof(CompilerGeneratedAttribute).FullName))
Problems.Add(new Problem(GetResolution(new object[0], member)));
return Problems;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Rules FriendlyName="FxCop rules">
<Rule TypeName="NameTaskReturningMethodAppropriately" Category="Tier3.FxCop" CheckId="TT1203">
<Name>Name Task-returning method appropriately</Name>
<Description>Methods which return Task or Task&lt;T&gt; must be suffixed with 'Async'.</Description>
<Url></Url>
<Resolution>Methods which return Task or Task&lt;T&gt; must be suffixed with 'Async'.</Resolution>
<Email></Email>
<MessageLevel Certainty="100">Error</MessageLevel>
<FixCategories>NonBreaking</FixCategories>
<Owner></Owner>
</Rule>
</Rules>
using System;
using System.Threading.Tasks;
public class NameTaskReturningMethodAppropriately
{
// Triggers TT1203
public Task TriggersRule()
{
return Task.FromResult(0);
}
// Does not trigger TT1203
public void DoesNotTriggerResult()
{
Func<Task> lambda = () => Task.FromResult(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment