dotnet/runtime

Analyzer for STAThread attribute applied to async Main

Open

#78.502 geöffnet am 17. Nov. 2022

Auf GitHub ansehen
 (3 Kommentare) (7 Reaktionen) (0 zugewiesene Personen)C# (5.445 Forks)batch import
api-approvedarea-System.Threading.Taskscode-analyzerhelp wanted

Repository-Metriken

Stars
 (17.886 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 12T 11h) (661 gemergte PRs in 30 T)

Beschreibung

Describe the problem you are trying to solve

When the [STAThread] attribute is applied to an async Main method, it does not have the intended effect (the main thread of the application is not created with the single-threaded apartment state). Since this gotcha seems to be fairly common (see e.g. https://github.com/dotnet/roslyn/issues/22112 and the issues linked to it), users should be made aware of it.

Describe suggestions on how to achieve the rule

I'm not certain if a code fix is necessary, but it could remove [STAThread] from the async Main method and then do one of the following:

  1. Add Thread.CurrentThread.SetApartmentState(ApartmentState.STA); at the start of the async Main method.
  2. Rename the async Main method to MainAsync and then add [STAThread] static void Main() => MainAsync().GetAwaiter().GetResult();.

Contributor Guide