Stop wasting server resources by properly using CancellationToken in .NET

preview_player
Показать описание

This video was sponsored by Skillshare

Hello everybody I'm Nick and in this video I am going to show you how you can properly use the CancellationToken struct in your .NET and ASP.NET Core applications in order to cancel tasks and operations early and prevent wasting valuable server resources.

Timestamps
ASP.NET Core implementation - 0:00
Console app implementation - 7:10

Don't forget to comment, like and subscribe :)

Social Media:

#cleancode #cleancoder #dotnet
Рекомендации по теме
Комментарии
Автор


This video was recorded before the release of .NET 6 which will bring the ability to reuse a CancellationTokenSource, which means that you won't have to dispose it. That being said, I did not want include that in the video since .NET 6 it is still not finalized.

nickchapsas
Автор

TaskCanceledException inherits from OperationCanceledException, so you only really need to catch the latter.

danspark
Автор

As a C# Dev your videos are extremely helpful. Thanks for your hard work.

Jonathan_Henderson
Автор

TaskCanceledException is a subclass of OperationCanceledException, so catching the latter will catch the former.

On disposing of the CancellationTokenSource, it can only safely be disposed if there are no remaining cancellation tokens hanging off it, and is only required if it is not going to be cancelled. Calling Cancel on the CancellationTokenSource does the same cleanup as calling Dispose, without risking an unexpected ObjectDisposedException when something tries to use a CancellationToken linked to it.

klightspeed
Автор

No one has explained CancellationTokens as well as you have

matthewtrip
Автор

Way clearer now ! thank you so much Nick for your videos

thibaudgalland
Автор

Thank you for the video. This approach was extremely handy when I worked on file uploading/downloading. Implemented TaskCancellation approach with a middleware.

ilyakurmaz
Автор

AFAIK, we should be catching OperationCanceledException. It will be raised in some scenarios, like a call to OperationCanceledException is the base class, and will be emitted in all cases of cancellation.

Inheritance: Object -> Exception -> SystemException -> OperationCanceledException
Derived:

AngusMcIntyre
Автор

I'd like a video in Funcs and extension methods!

DoorThief
Автор

I've seen technical explanations of cancellation tokens before, but no one has really put it in the context of saving resources - which is a 'super' important thing. Great vid.

mirata
Автор

Good stuff, Nick. It's worth noting that, when working with Azure Functions, there are 2 potential cancellation tokens. One from the caller and one from the Host (APIM). In which case you can use a LinkedTokenSource.

coboi
Автор

This was a great explanation! Thanks a lot for the video!

joaonadais
Автор

hi nick. IdentityServer4 videos will be perfect if you create

raminquliyev
Автор

Thanks Nick!
In the Postman example, you hit a "cancel" button which somehow simulates closing the browser, right? What if you wanted to have a "cancel" button on your webpage? How would you trigger the cancellation in a web app without closing the browser? In other words, if you wanted to provide a way for a web user to cancel a long calculation they had already started, how would you do that? It's clear how to do it in a console app, but in a web app you have to worry about which httpcontext, right?

spuriustadius
Автор

Interesting video, in our case we ended up not implementing it after seeing that most immediately made the request again after cancellation as it was usually an accidental navigate away and all requests end up cached in Redis anyways, there's more than enough cache that DB doesn't get hit that hard, DB is way over-provisioned for when reports are generated.

Masterrunescapeer
Автор

I'm a bit confused on your usage of Dispose(). The method doesn't "own" the CTS (it was passed in), so shouldn't it be left up to the owner to determine when it's done with the CTS resource and when to dispose of it?

Tsunami
Автор

Thank you for explaining that .
is it worth adding the cancellation token if I'm just get small amount of data, like on user info ?

rawanabodyak
Автор

C# can learn something from Kotlin - learn coroutine, and avoid checking tokens.

nayanchoudhary
Автор

Great explaination. I'm missing the part where a method is declared with a default cancelation token. eg: public void DoAsync(CancelationToken cancel = default).
Where is the default CancelationTokenSource

Автор

Hi Nick, can u make a playlist videos that build start App complete with management menus, jwt api, authentication & authorization, additional userClaim for example: userCompany, userId, UserFullName, userRoles(multiple role per User)
Registration & login auth using google
Thanks

yoshkoneski