Skip to content

JoinableTaskContext.IsOnMainThread should satisfy VSTHRD010 #1100

Open

Description

@zivkan

Is your feature request related to a problem? Please describe.

Previously commented in another issue: #272 (comment)

I have a method I want to be free-threaded, but I have dependencies which are not. How I implement my method depends whether it's running on the main thread, or a background thread. Copying the example from the other issue:

public void NotAffinitized() {
  if (IsOnMainThread()) {
    // This incorrectly marks the enclosing method as affinitized, which then propagates
    SomeAffinitizedMethod();
  } else {
    SomeNonAffinitizedMethod();
  }
}

Describe the solution you'd like

No VSTHRD010 within the if block.

Describe alternatives you've considered

An await jtf.SwitchToMainThreadAsync(alwaysYield: false) does suppress the warning, but feels inefficient. Even if it's fast, it's still extra work that isn't necessary for program correctness, just to satisfy the analyzer.

Additional context

Activity

  1. zivkan commented on Oct 29, 2022

    @zivkan
    MemberAuthor

    Here's some test code that I believe should be made to work:

            var test = @"
    using System.Threading.Tasks;
    using Microsoft.VisualStudio.Shell;
    using Microsoft.VisualStudio.Shell.Interop;
    using Task = System.Threading.Tasks.Task;
    
    class Test
    {
        void Foo()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            IVsSolution solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;
        }
        async Task FirstAsync()
        {
            if (ThreadHelper.JoinableTaskFactory.Context.IsOnMainThread)
            {
                Foo(); // this generates a warning, even though Reset() doesn't assert
            }
        }
    }
    ";
            await CSVerify.VerifyAnalyzerAsync(test);

    However, I haven't yet been able to get the product code to make the test pass. I don't have any experience with the Roslyn APIs, so it's a learning curve to contribute. As much as I'd love to get my own name in the commit history, if someone else can get this implemented before me, I'll be happy to be able to take advantage of the improvement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions