Skip to content

VSTHRD003 False positive in top-level statements #1370

Closed

Description

Bug description

The VSTHRD003 is triggered when using a combination of Task.Run and Task.WhenAny in a "top-level statements" (programs without Main methods) console app

Repro steps

This "top-level statements" code will trigger VSTHRD003

using var cts = new CancellationTokenSource();
      
var loopTask = Task.Run(
    async () =>
    {
        // DO SOMETHING...
    },
    cts.Token);

var serverTask = Task.Run(
    async () =>
    {
      // DO SOMETHING...
    },
    cts.Token);

var exitTask = Task.Run(
    () =>
    {
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        cts.Cancel();
    },
    cts.Token);

await Task.WhenAny(loopTask, serverTask, exitTask);  /// VSTHRD003 is triggered here !
Console.WriteLine("Exited");

This traditional console app, on the other hand, does not trigger VSTHRD003

public static class Program
{
    public static async Task Main(string[] args)
    { 
        using var cts = new CancellationTokenSource();
      
        var loopTask = Task.Run(
            async () =>
            {
                // DO SOMETHING...
            },
            cts.Token);

        var serverTask = Task.Run(
            async () =>
            {
              // DO SOMETHING...
            },
            cts.Token);

        var exitTask = Task.Run(
            () =>
            {
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                cts.Cancel();
            },
            cts.Token);

        await Task.WhenAny(loopTask, serverTask, exitTask);  /// VSTHRD003 is NOT triggered here !
        Console.WriteLine("Exited");
    }
}

Expected behavior

VSTHRD003 should not be triggered in this scenario

Actual behavior

VSTHRD003 is triggered in this scenario, and it shouldn't

  • Version used: 17.12.19.10947
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions