dotnet/runtime
Voir sur GitHubAnalyzer for STAThread attribute applied to async Main
Open
#78 502 ouverte le 17 nov. 2022
api-approvedarea-System.Threading.Taskscode-analyzerhelp wanted
Métriques du dépôt
- Stars
- (17 886 stars)
- Métriques de merge PR
- (Merge moyen 12j 11h) (661 PRs mergées en 30 j)
Description
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:
- Add
Thread.CurrentThread.SetApartmentState(ApartmentState.STA);at the start of theasync Mainmethod. - Rename the
async Mainmethod toMainAsyncand then add[STAThread] static void Main() => MainAsync().GetAwaiter().GetResult();.