Are You Using Cancellation Token The Right Way? 5 Recommended Patterns | Exploring C# and DOTNET

Опубликовано: 26 Март 2024
на канале: Rahul Nath
2,126
142

CancellationTokens in .NET allows the caller to express lost interest in the result of an operation. This can be at a Function level, class level, API endpoint, etc.

But does that mean all requests are the same and can be canceled similarly? Short answer - No!

So, let’s learn some recommended practices when using Cancellation Tokens in your application code. Here are five recommended patterns to use as a guide when working with CancellationTokens in .NET

1. Avoid canceling operations after side effects to prevent inconsistencies in the application state.
2. Optional on Public API and required everywhere else (Make it an intentional choice to pass on the `CancellationToken`)
3. Use `CancellationToken.None` after the point of 'no cancellation' (has incurred side effects)
4. Check `CancellationToken.CanBeCancelld` if your functions can be more efficient when the tokens can't be canceled. (`Task.Delay` is a good example of this.)
5. Ignore `CancellationToken` if work is very quick.

00:00 Introduction
01:15 Should all Functions be Cancellable?
05:02 1. Avoid Cancelling After Side-effects
06:40 2. Mandate CancellationToken in Functions
08:09 3. CalcellationToken.None
10:01 4. CancellationToken.CanBeCancelled
11:35 5. Ignore CancellationToken

Thank you to AWS for sponsoring this video.

🔗 Cancellation Token - https://www.rahulpnath.com/blog/cance...
🔗 Code - https://github.com/rahulpnath/youtube...

Additional Watching
📹Cancellation Token -    • Cancellation Token in .NET | Explorin...  
📹C# Series - https://bit.ly/mycsharp
📹 ASP Series - https://bit.ly/asp-net-core-series
📹Azure Series - https://bit.ly/azure-series
📹AWS Series - https://bit.ly/aws-net-series
📹RabbitMQ Series - https://bit.ly/rabbitmq-net-series

Come say hi! ✋
🎙️Uses - https://www.rahulpnath.com/uses
🌍Blog - https://www.rahulpnath.com/
✉ Subscribe to my Newsletter - https://www.rahulpnath.com/subscribe
🐦Twitter -   / rahulpnath  
📸Instagram -   / rahulpnath  

#dotnet #csharp


Смотрите видео Are You Using Cancellation Token The Right Way? 5 Recommended Patterns | Exploring C# and DOTNET онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Rahul Nath 26 Март 2024, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 2,12 раз и оно понравилось 14 людям.