🔥 How to use CancellationToken in ASP.NET Core WebApi

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone I'm Saeed today we are going to talk about cancellation token and how we can use cancellation token in our web API I try to cover all of the scenarios for using the cancellation token before we go into the code I got a question for you imagine that you have an API that is calling by front end and user there is a button in your website user will press that button and before server return the response user will close the browser or refresh the website what happened to that operations on the server side I mean imagine that you are running a query on the database or running a task but actually that request is already gone it's disconnected what happened is it still running on server side or it will cancel think about it okay um I prepared a very simple uh project uh using the default template for the asp.net and let me run the project here um okay I have Swagger page okay this is the our Swagger page here is uh we have four apis uh uh we have an API without cancellation token and after we try to use cancellation token source another one is request cancellation and finally we are going to check Entity framework queries with cancellation token so for the first API let me run this API first of all uh in this video I'm not going to talk about asynchronous task how we can use it how it works if you like this subject uh please leave a comment for me and after I can create another video for that subject so this API if we check the code here there is a method that is actually uh doing nothing just 30 second running for this for Loop and every second it will lock something that shows the task is running okay I pass a number just for showing the different tasks and this cancellation token the default one default value for cancellation is cancellation token none which means it's nothing so let me run this API and if we check the log here you can see that task is running but let me here in this browser Let me refresh the browser browser is refreshed but as you can see here task is running so that question for the if user cancel the request or refresh the browser all the tasks on server side is still running until is done in this case this task will run for 30 seconds so this is very bad because in this 30 seconds this task will use our server resources and another bad thing is think about if we run a query on your database and what happened okay so let's uh going to the next API and see we can use the cancellation token first scenario here is using cancellation token Source this cancellation token is actually create a source for our tasks that is using some scenarios for creating cancellation token and when we use that cancellation token if it's fired I mean if it's canceled actually all the tasks will notified and will be canceled so here when you want to create a cancellation token there is a overload that accept expiration time so this one I passed 10 seconds for it so it means if I run this query this task will run for 10 seconds and after will be canceled if before 10 seconds your task will return the response everything okay so that if I call this API you can see there is another task created and it will run for 10 seconds yeah there is exception called this task cancellation exception and the message is a task was canceled so it's good in case of saving the resources because in case of any users close the web browser or your website you can be sure that after 10 seconds your task will be finished and of course you need to handle the exceptions but we want to see this cancellation token okay but this one is good but not good enough because if you want to for example after one second uh user will close the browser or cancel the request but it still will run for 10 seconds so what is the next scenario ex solution for using the cancellation token in we can use cancellation token in the every hour actions so by default asp.net pipeline will pass this cancellation token to all of our actions so we can use it as a parameter like this so if we use this cancellation token we can pass it to the all the tasks and then if a request canceled this one will fire and this task will be canceled but let's check it another one is using this one okay another test running but let's me let me refresh the browser and yeah you can see right after we refresh the browser this task is canceled so this is very good because um right after our user cancel the request this uh the all of the tasks in the our application on on server side will be canceled so this is what we want but this scenario this case is a little uh annoying because if I want to add this parameter to all of our actions it can be a little messy in our application the better way is to use the HTTP context so in the HTTP context object we have the probability of requests about it this one is actually that cancellation token that is passed by the HTTP context so maybe you asked this question to yourself that how and when this cancellation token uh created or set to canceled actually we need to care about the HTTP context here where HTTP context created at the first place so this HTTP context actually created by web servers so in this case our default web servers in asp.net core is casual so it means every request first goes to the Kestrel and then Kestrel will redirect and pass that request to our actual asp.net pipeline but before passing that request it will create this object this HTTP context object and set all of these kind of I don't know the properties like client IP like the other rest of the properties about the current request and when uh request canceled canceled I mean refreshing browser or closing browser closing that tab actually that connection will be disconnected from the server so the cash flow will notify that this request is no longer connected to the server and then it will set this cancellation token to the HTTP context so if we use this one uh actually all of these subsequent tasks will notify and will be canceled when I say uh all subsequent tasks and layers I mean the best practices is not only use this cancellation token in the representation layer actually it has nothing if only we pass like uh to this task if this task calling another layers of our application for example currently we are here in API layer but maybe you have another layer called service and actually maybe you have another one like Repository yes so we need to pass the same cancellation token to all of the other layers so that if the first layer will cancel notify this cancellation token all of these tasks in the other layers will be canceled okay so uh we can use this one as well it's way better than passing the cancellation token as a parameter and it's the same as even in the minimal API you can use this parameter for cancellation token or in the HTTP context as a parameter okay uh the last one actually the more interesting one uh is for um checking the Entity framework cancellation so if we run a query a bigquery in our application and run that query against the database for example it takes 10 seconds to run but in meanwhile a user will cancel the request what happened so there is two sides in our application one in the application side and one in the database side so first a step is Entity framework will translate the link query to the tsql and then pass this tsql to the database to run okay if cancellation token canceled in application side it's okay no problem we actually saw this step but how about the database I mean actually your query will pass to that to the database and it's not in your application anymore so let's see let's see uh how we can check it so for this scenario I just create a database and contains the test table but for the simulating this kind of delay there in the SQL Server um you can put some delay in your queries using wait for delay so here it before running this query it waits for 10 seconds and then run this query so let me run it in the database here uh okay so you you see that here it will wait for 10 seconds and then run the second part of the query yeah but I mean if I comment the the delay it will run immediately see okay so actually this query will takes 10 seconds to run let me run the project so in meanwhile for checking actual um cancellation token and see if the query is canceled we need to use a tool in the SQL Server called SQL Server Pro profiler yeah you can connect to our database and here I need to select all of this column here and actually I need to check this error column in the tsql batch completed so I just need to check it here and run the query so this uh monitoring will Trace all of the queries against your database and if I run this API here actually this one is running so as you can see there is some Trace here that see the this command the actual command is running and this one is uh when it's completed batch is completed and in the error let me drag it here okay as you can see this uh query runs successfully without any issues okay but uh okay and here it's returned done if I run it again and batch a start and just I want to refresh this browser okay and you can see but first uh let me check this yeah patch completed this command you can see in the profile layer but the beautiful one is here it seems It's a bird it's a burden it means actually query will be canceled in the database as well yeah it's very nice it means Entity Framework will cancel their task in the application side and the odd all of the queries that actually running in the database side as well so you can be sure that all of these resources that Acquire by the database or the application will be released when the task is uh canceled and actually we can see in the application side you got some exceptions for the cancellation called operation canceled by user in case of the Entity Framework okay so we saw that using cancellation token actually this is all of the scenarios I cannot see any other scenarios for using the cancellation token if you know anyone else you can comment in this video and uh yeah uh cancellation token is very very good uh things for managing your resources and nowadays because in our our of all our application we are using the asynchronous we are using task so using this cancellation can be very useful for managing the resources for releasing this kind of locking in database side or even third-party services third-party apis you need to pass this cancellation in the HTTP clients as well everywhere that there is a possibility for uh using this cancellation will be useful you can comment in this video if you want to know more about cancellation token and actually how it works behind the scenes I don't want to create a very long video but this can be a very interesting topic to see how it works behind the scenes how tasks handle this situation if they are using this cancellation uh so there is some scenarios for registering the some callback for the cancellation token or checking the um some properties is request canceled or is cancellation token uh some Boolean values uh so all uh these scenarios can be useful for your application thank you very much for watching this video don't forget to subscribe my channel there is a lot of video coming and I'm sure that we will have a lot of fun together thank you
Info
Channel: Saeed Esmaeelinejad
Views: 6,927
Rating: undefined out of 5
Keywords:
Id: c8rZ5r-CdrE
Channel Id: undefined
Length: 20min 53sec (1253 seconds)
Published: Tue Sep 26 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.