Comments (8)
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.
I don't have write-permissions, but this should be regarding the roslyn compiler, not the analyzers.
from roslyn.
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.
@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.
@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.
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 await
ed, nor its Result
get accessed.
from roslyn.
from roslyn.
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)
- `ref` modifier keyword is missing from completions for `ref struct` primary constructor parameter definition
- Source Generator generated code cannot be compiled HOT 10
- Check if ModuleCancellationInstrumenter gracefully handles ref kind differences between original and replacement methods HOT 1
- Saving an AdditionalFiles document in Balanced mode fails to trigger source generator HOT 1
- Tests failing with BadImageFormatException
- [Automated] PRs inserted in VS build main-35115.160
- Name of ```AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute``` implies wrong location of the ```OutAttribute``` type
- Generic extension method on generic type with `LangVersion=preview` and `Nullable=enable` crashes compiler with `NullReferenceException` in `ConstraintsHelper.CheckConstraints` when accessing non-existent member of extension method's name on type
- MSBuildWorkspace should have unit tests running on mono
- error RZ3600: Invalid value ''' for RazorLangVersion. Valid values include 'Latest' or a valid version in range 1 .0 to 8.0 HOT 8
- [Bug]: funny interaction between verbatim strings and the preprocessor HOT 3
- Syntax highlight colors differ between Dark and System modes HOT 4
- How to prevent visual studio from inserting <see langword=""/> in comments HOT 1
- Hovering over a method gives the wrong overload
- Syntax highlight is half broken in both VS 17.10 and VS 17.11 P3
- False positive CS8618 null reference type warning when using required members and [SetsRequiredMembers] in derived class
- C# rename default constructor argument which is used as a property HOT 1
- Replacing using System with #include <stdio.h> in Roslyn C# Syntax Tree Rewriter HOT 3
- Debug assert triggered for interpolated string convserion
- "dotnet build-server shutdown" warning for missing dll HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from roslyn.