0

There are a lot of Question and Answer about the async void theme. And we all agree this is not a good thing, and I believe in all cases is avoidable. That Is why I want to create a Visual Studio Error Message when it is used.

In other cases it was success, like: When a function returns with Task the visual studio makes a warning CS4014. And we configured the handle to this warning as error with Directory.Build.props mechanism. Here is the code of it:

<Project>
  <PropertyGroup>
    <WarningsAsErrors>CS4014</WarningsAsErrors>
  </PropertyGroup>
</Project>

As you can see the CS4014 as handled like an error. It is works fine. But for async void there is no warning message, that is why we cannot configure to handle this as an error.

Is there any way to add custom error/warning messages to msbuild build process?

To create own error/warning messages will be very helpful in lot of cases.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
György Gulyás
  • 1,290
  • 11
  • 37

2 Answers2

0

Is there any way to add custom error/warning messages to msbuild build process?

There is a VS extension called AsyncFixer that can detect async void methods.

However, it just turns these async void methods as warnings rather than errors. And it seems that WarningsAsErrors xml mode does not work for it.

So if you still want to treat them as errors, I suggest you could create a new configuration called Production in VS IDE and then add them in Directory.Build.props:

<Project>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Production|AnyCPU'">
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
</Project>

In this Configuration, it will treat every warnings as errors and it is easy for you to find each async void methods. (This is a better function which l have tested for your issue). After it, you can change Configuration back to any other else to build your project. It will

More about this function, you can refer to this related case.

In addition, if it still does not satisfy you, you should create an analyzer to detect Async Methods.

jessehouwing
  • 106,458
  • 22
  • 256
  • 341
Mr Qian
  • 21,064
  • 1
  • 31
  • 41
0

The mentioned AsyncFixer extension and Nuget Package are super useful when dealing with async code. They both package a Roslyn analyzer that detects many async issues and provides an automatic fix for them as well in most cases.

Using the .editorconfig in Visual Studio you can configure specific warnings as errors:

[*.cs]

# AsyncFixer03: Fire-and-forget async-void methods or delegates
dotnet_diagnostic.AsyncFixer03.severity = error

And you can set that straight from the Solution Explorer in case you've added AsyncFixer as a nuget package:

enter image description here

By adding the extension as a nuget package, it also automatically works on any CI server that builds your code without any further installation.

jessehouwing
  • 106,458
  • 22
  • 256
  • 341