Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CancellationTokenSource in using block inconsistently triggers AsyncFixer04 #28

Open
evieeddins opened this issue Oct 12, 2022 · 0 comments

Comments

@evieeddins
Copy link

I'm using a CancellationTokenSource for two asynchronous actions, then awaiting them using Task.WhenAny

But this is triggering AsyncFixer (Code AsyncFixer04) in a way that I don't understand.
If I set the scope of the CancellationTokenSource with a using statement in brackets, like so

using System.Threading;
using System.Threading.Tasks;

namespace AsyncFixerIssue
{
    internal class Program
    {
        static Task Main(string[] args)
        {
            using (var cts = new CancellationTokenSource())
            {
                var a = Task.Delay(1, cts.Token);
                var b = Task.Delay(1, cts.Token);

                return Task.WhenAny(a, b);
            }
        }
    }
}

it triggers a warning from AsyncFixer04.

But if I format it like this, there's no problem

static Task Main(string[] args)
{
    using var cts = new CancellationTokenSource();
    var a = Task.Delay(1, cts.Token);
    var b = Task.Delay(1, cts.Token);

    return Task.WhenAny(a, b);
}

Also, I can just set cts.Token to a variable and make the analyzer happy

static Task Main(string[] args)
{
    using (var cts = new CancellationTokenSource())
    {
        var cancellationToken = cts.Token;
        var a = Task.Delay(1, cancellationToken);
        var b = Task.Delay(1, cancellationToken);

        return Task.WhenAny(a, b);
    }
}

It seems like either all of these should trigger the analyzer, or none of them should.
Is this a bug?
If not, what's your recommended fix for passing along a CancellationTokenSource?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant