How to Cancel Tasks in C# - Using CancellationTokenSource and CancellationToken

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone brian lagunas here and today i'm going to answer another tech question if you have a tech question you'd like to have answered be sure to subscribe to my channel like this video leave a comment below with your own question and i may just answer it in my next video now today's question comes from my comments if you've seen any of the previous videos that i've done recently all about async await and task you'll see that a common question is well brian this is all great i love async and wait i love task i know all about configure weight and how to report progress and all this great stuff but uh how do i cancel it well the answer this is it really depends there are multiple ways to cancel a process in an application there are many ways to cancel a task and the way you cancel a task really depends on the implementation of that task what i mean by that is maybe you have a long running process that's going through some type of recursive loop uh and you're gonna pull the property and poll for cancellation or maybe you're gonna handle some type of callback maybe the api you're using doesn't accept a token but you still need to cancel the task so you can use a callback to do that or maybe you're going to use the weight handle right i mean what i'm trying to say are there are multiple ways to cancel a task depending on what you're doing so in this video i thought that i would build on a previous video in which we showed reporting progress and we were looping through a whole bunch of numbers right so we're going to use the polling approach today to cancel a long-running task so enough of this diddle daddle talking chit chat let's go ahead and get to the code roll that intro [Music] the application we'll be working with today is the same application that we used in our video that showed how to report progress to our end users for a long running task as you can see we have a button click event handler in which we are running a long running process called loot new numbers this loop new number simply loops through numbers and then reports the percent complete of that process to our end user and we set the progress bar and text block to that percent value let's go ahead and run the application and see how it functions here's the application running as you can see we click the loop through numbers button and the process kicks off in which we report the progress of this process what we want to do is we want to modify this application to implement this cancel button the expectation is when i click the cancel button no matter where we are in the process of the loop do numbers function we will cancel the task and prevent it from running any further so let's go ahead and implement that now the first step to canceling a task is to create what's called a cancellation token source so we'll create a cancellation token source or call this token source and for now we will set it to null in our button click event what we want to do is we want to create an instance of our token source a cancellation token source is simply an object that creates a cancellation token and it's also used to issue the request for cancellation so what we want to do is we actually want to grab the token that the token source has created for us so we'll say tokensource.token the token is essentially a value type that's passed into one or more listeners this is normally done through a method parameter meaning we have to pass this token into our loop through methods where the cancellation will occur so let's add a method parameter to our method here which is of type cancellation token and let's make sure we pass in the token to our method we monitor the value of the is cancellation requested property by polling so what i mean by that is let's say if the token dot is cancellation requested we know that the request to cancel this task has been invoked this is where for example we would do some type of cleanup code and then we have some options on how we handle the cancellation of this task now it's called polling because as we loop through this method we are continuously checking the is cancellation request property so we are polling that property each time through each loop once we discover that this task has been requested to be cancelled we have some decisions to make to decide how we're going to actually handle the cancellation one option may be to just throw an exception uh maybe you just return maybe we just say you know what we're just going to return out of this right and just break clean another option may be you're dealing with results and you want to return a modified result well in our case what i'm going to do is i'm going to throw an exception the recommended way to throw an exception is actually to use the token that throw if cancellation requested so what this means is when we come up to our task to handle this cancellation what we want to do is we want to wrap this into a try catch block now the type of exception that we're going to catch is what's called an operation cancelled exception and here we will handle that exception in this case we'll say the textblock.txt equals cancelled now one more very important tip that i want to make sure you know about is we always want to dispose of the token source so let's add a finally block and in here we're going to say token source dot dispose and finally we have to actually invoke the cancellation this is probably the easiest part we're simply going to go to our cancel button click event and we're going to say tokensource.cancel let's go ahead and run our application and see what happens here's the application running we're going to click the loop through numbers button we can see that we are looping through our numbers and i'm going to click our cancel button and we have an exception which is great because that means that through this loop we have polled the is cancellation request property it is true we're going to do some cleanup code here and after that cleanup code we threw the exception so now we're going to continue through this and we can see that we have properly handled that exception and now we have updated the ui and said canceled and our progress bar has been stopped at the point of cancellation and that's it that's how easy it is to cancel a task using polling of the is cancellation requested property on a token [Music] you
Info
Channel: Brian Lagunas
Views: 17,299
Rating: 4.9248433 out of 5
Keywords: how to cancel tasks in c#, cancel task with cancellationtoken, cancellationtoken c#, cancellationtokensource c#, cancellationtoken c# task, cancellationtoken example c#, cancellationtokensource example, cancellationtokensource tutorial, cancellationtokensource async await, cancellationtoken cancel task c#, cancellationtoken example, cancellationtokensource cancel, cancellationtokensource, cancellationtokensource example c#, cancellationtoken .net core, cancel task C#
Id: TKc5A3exKBQ
Channel Id: undefined
Length: 6min 23sec (383 seconds)
Published: Thu Aug 06 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.