vs-threading icon indicating copy to clipboard operation
vs-threading copied to clipboard

VSTHRD010 raises a false positive with eager linq queries

Open nkolev92 opened this issue 5 years ago • 0 comments

Bug description

VSTHRD010 flags a false positive when the access to the object that requires the main thread is done in a linq statement that's eager.

Repro steps

See attached project :)

AnalyzerFalsePositive.zip


        public static async Task<EnvDTE.Project> GetProjectAsync(EnvDTE80.Solution2 solution2, string projectName)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            return solution2
                .Projects
                .Cast<EnvDTE.Project>()
                .FirstOrDefault(project => project.Name.Equals(projectName, StringComparison.OrdinalIgnoreCase)); // One that can potentially be improved.
        }

This incorrectly raises a warning.

By contrast this warning is correct:

        public static async Task<IEnumerable<EnvDTE.Project>> GetProjectsAsync(EnvDTE80.Solution2 solution2, string projectNamePattern)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            return solution2
                .Projects
                .Cast<EnvDTE.Project>()
                .Where(project => project.Name.Contains(projectNamePattern)); // Correctly flagged pattern.
        }

Expected behavior

No warning :)

Actual behavior

The warning was raised :)

  • Version used: Microsoft.VisualStudio.Threading.(Analyzers) versions: 16.4.43
  • Application (if applicable):

Additional context

This was raised in our test code: https://github.com/NuGet/NuGet.Client/blob/cb402b5a3340ab5b2605ecc72de7f70aaac95344/test/TestExtensions/API.Test/VSSolutionHelper.cs#L463-L471

nkolev92 avatar Dec 27 '19 00:12 nkolev92