Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why CancellationToken is a struct?

Does it make any sense to use a struct instead of a reference type in case of CancellationToken?

I see one possible disadvantage, it will be copied all the way down in methods chain as I pass it as a parameter.

In the same time, as far as it is struct, it might be allocated and disposed faster.

If we want to make it immutable, we can use readonly properties or private setters.

So what was an idea behind it?

like image 297
Neir0 Avatar asked Oct 22 '18 20:10

Neir0


People also ask

What is a CancellationToken?

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource. Token property.

What is difference between CancellationTokenSource and CancellationToken?

CancellationTokenSource - This is the object responsible for creating a cancellation token and sending a cancellation request to all copies of that token. CancellationToken - This is the structure used by listeners to monitor the token's current state.

What is CancellationToken in .NET core?

You can use a CancellationToken to stop a long running operation when the user cancels a request in the web browser. In other words, using a CancellationToken can help you stop long running requests from using resources when the user has stopped or refreshed the web page.

Can a CancellationToken be reused?

Therefore, cancellation tokens cannot be reused after they have been canceled. If you require an object cancellation mechanism, you can base it on the operation cancellation mechanism by calling the CancellationToken. Register method, as shown in the following example.


1 Answers

There is an article that describes the .NET Cancellation design here which is worth a read. In relation to your question, the following is asked in the comments:

Just out of interest, why is the CancellationToken a value type?

and the questioner proposes an alternative implementation with a single shared instance of CancellationToken as a reference type.

And the response by Mike Liddell:

This would certainly work and is largely equivalent (and we implemented it this way during early prototyping), but we went with the current design for two particular reasons:

– only one class instance per CTS/Token, hence less GC pressure.

– we consolidate all of the state and most of the logic onto CTS. The split arrangement was a somewhat more convoluted.

I would note that the current value type implementation is exactly the same size as a reference so there isn't any additional copying overhead. It also prevents some additional boilerplate null checks in user-code, especially when making the token an optional parameter.

like image 149
Mike Zboray Avatar answered Oct 16 '22 15:10

Mike Zboray