Giter Site home page Giter Site logo

Comments (8)

dotnet-issue-labeler avatar dotnet-issue-labeler commented on July 18, 2024

I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

from roslyn.

EdLichtman avatar EdLichtman commented on July 18, 2024

I don't have write-permissions, but this should be regarding the roslyn compiler, not the analyzers.

from roslyn.

huoyaoyuan avatar huoyaoyuan commented on July 18, 2024

The compiled code of simplified using and traditional using should be same. They are both lowered into following structure:

var obj = using_obj;
try
{
    do_something;
}
finally
{
    obj.Dispose();
}

If exception happens in do_something, the Dispose will still be invoked.

If I modify your code like this:

    public static Task RunChildWithManualDisposal(CancellationToken parentToken)
    {
        // Within an asynchronous task, 
        Task.Run(async () =>
        {
            // create the linked token source
            var currentTokenSource = CancellationTokenSource.CreateLinkedTokenSource(parentToken);
            //grab reference to only the token.
            var childToken = currentTokenSource.Token;
            try
            {

                // await a task that should be cancelled by the parent token
                await Task.Run(
                    async () =>
                    {
                        // Log information about the running tokens
                        _ = Task.Run(async () =>
                        {
                            while (!childToken.IsCancellationRequested)
                            {
                                await Task.Delay(TimeSpan.FromMilliseconds(500));
                                LogTokenCancellation(parentToken, nameof(parentToken));
                                LogTokenCancellation(childToken, nameof(childToken));
                            }
                        }, childToken);
                        childToken.Register(() => Console.WriteLine("{0} has been cancelled", nameof(childToken)));

                        // figure out how to break out of this task with a completion source
                        var completeTask = new TaskCompletionSource();

                        // Delay for 5 seconds, then cancel the child.
                        await Task.Run(async () =>
                        {
                            await Task.Delay(TimeSpan.FromSeconds(3));
                            completeTask.SetResult();
                        }, childToken).ContinueWith(
                            (task, state) =>
                            {
                                Console.WriteLine("Finished setting result.");
                            },
                            new(),
                            parentToken);

                        // wait (forever) until this task breaks
                        await completeTask.Task;
                    }, parentToken);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex}");
                throw;
            }
            currentTokenSource.Dispose();
        });
        return Task.CompletedTask;
    }

It will print that exception is thrown, so your manual Dispose is never invoked. That's the source of behavioral difference.

When a linked cancellation token is disposed, it dissociates its link with upstreams. So your child token will not be canceled by parent token. In fact, a disposed CancellationTokenSource will never become canceled from uncanceled because all cancellation mechanisms are disposed. It will remain the state at the moment it was disposed.

from roslyn.

genlu avatar genlu commented on July 18, 2024

@huoyaoyuan thanks for looking into this!
@EdLichtman This sounds like an issue in your code. I'm closing it as it's not a roslyn bug, but feel free to continue discussion here

from roslyn.

EdLichtman avatar EdLichtman commented on July 18, 2024

@huoyaoyuan, thanks for responding. I am confused since, when I run ManualDisposal, there seems to be no error thrown, but when I wrapped it with a try/catch, it threw the exception. What causes this behavior? I'd imagine that if an error were to occur, it would be thrown regardless of being in a try/catch?

from roslyn.

huoyaoyuan avatar huoyaoyuan commented on July 18, 2024

What causes this behavior?

Because the top-level task is forgotten:

    public static Task RunChildWithManualDisposal(CancellationToken parentToken)
    {
        // Within an asynchronous task, 
        Task.Run(async () =>

It catches exceptions from child task, but nobody handles the exception in top-level task, because it's not awaited, nor its Result get accessed.

from roslyn.

EdLichtman avatar EdLichtman commented on July 18, 2024

from roslyn.

huoyaoyuan avatar huoyaoyuan commented on July 18, 2024

It does not fire off correctly.

You don't include a finally -> the Dispose is not called -> the link between child CancellationTokenSource and parent is not dissociated -> you can observe the cts as cancelled.

Otherwise, when you use using,
using statement uses finally -> the Dispose is not called -> the link between child CancellationTokenSource and parent is dissociated -> it will never be canceled in any way.

You are giving incorrect expectation to CancellationTokenSource. Once disposed, the instance will be immediately frozen and disconnect with any signals.

from roslyn.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.