Roslyn: Attributes applied to async entrypoint method does not have effect

Created on 11 Jul 2019  路  6Comments  路  Source: dotnet/roslyn

Version Used:
Visual Studio 2019 d16.3

Steps to Reproduce:

  1. Assume I am creating an app for COM interop that requires STA Thread. Create a netcoreapp3.0 Console and reference WinRT contract package
  2. Write the code like this
    c# [STAThread] static async Task Main() { Console.WriteLine(Thread.CurrentThread.GetApartmentState()); }

Expected Behavior:
Expected to output "STA"

Actual Behavior:
Outputs "MTA" (C# language default)

If I change the Main method back from async to void, it outputs the correct thread state "STA".

I guess it is an issue where the attributes applied to the entrypoint method in code does not bring to the real entrypoint the compiler is generated.

Area-Compilers Bug Resolution-By Design

All 6 comments

I just hit this when trying to create a generic host for WPF apps where the entry point would be an async Main.

This has been previously discussed at https://github.com/dotnet/roslyn/issues/22112, where the conclusion was:

As mentioned in dotnet/csharplang#97, this was explicitly considered and rejected by LDM. [鈥

Regardless, this needs to be taken through the dotnet/csharplang repo and LDM before we'd consider a compiler change here.

This is a significant issue when dealing with UI apps, which were not necessarily being though of for .NET Core at the time of that LDM.

If you want to have an Async Main entrypoint of a WinForms or WPF app, this feature doesn't work at all, and leads to errors even when the user does what they expect should work.

The current behavior is by design. Do not use an async Main if this is not the behavior you want.

My point here is that the behavior is not obvious that making Main async would break the applied attribute. The attribute is applied and it would be expected to work. There's also no other easy way to apply the apartment state to the entry thread.

I personally disagree with a resolution by design. If this feature is not available for UI apps, it should error while compiling. When developers consider Async Main, they would think it will work always. It you tell them it doesn't work for adding attributes, they should know it in an easy way, either from a live code analysis, or somewhere documented. Leaving this without any warning will generate code with unexpected behavior and it can not be addressed before run.

I would like to propose following if LDM's rejection is unable to debate.

  • When a Main method is async, and one or more attributes are associated, generate a compiler error message on the Main method saying "The attributes applied to async Main will not apply to the underlying compiler generated entrypoint method."
Was this page helpful?
0 / 5 - 0 ratings