4:30 You don't need the if on line 43; ThrowIfCancellationRequested will throw only if cancellation is requested and won't do anything otherwise. Love these videos. Keep'em coming!
Right, but I was showing how to poll the property, then do some cleanup. If you used just ThrowIf... there is no opportunity for clean up. Thanks for watching
Small tip: in this code _tokenSource is null until the operation has been started, so pressing the Cancel button before you start the operation would cause a null-deref exception. You can easily protect against that by using the Elvis-operator like this _tokenSource?.Cancel(); You should also set _tokenSource back to null after you Dispose it otherwise pressing the Cancel button twice would also cause errors as it would be calling Cancel on the disposed _tokenSource.
@@BrianLagunas Absolutely. Was more just a heads-up for the viewer that decides to copy-paste the whole thing to production. Because there is always one 😁
I think the channels that have high numbers are more geared towards beginners. There are a few guys out there I know of that provide more advanced content, and they all seem to have the same "problem".
Great job explaining this, thank you. I like the approach you take with very simple blocks of code that get augmented with the cancellation part. Makes it more intuitive to follow along, much more than if you had started by showing the final code.
Thanks for the demo. Can you also demo something that has a "success token", to signal the completion of a long running task? Rather than using await to wait, the signal of the "success token" shall signal the completion of the task.
Hi Brian. Thanks for this video. Can we have this cancellation token implemented for Background Service as well - can we cancel the task via UI screen ?
Awesome explanation. Simple and concise within an applicable context. I went to MS first and their explanations out of a practical context just made their documentation useless.
Great videos!! I have in a script the following. await Task.Run( async () => { MyFunction(); } ); and I want to cancel MyFunction after 2 seconds. How do I do that?
many thanks for the great content :) there still seems to be some audio sync issue (on windows 10 firefox), just wanted to make you aware as I read in a previous comment you were trying to fix it :) keep up the good work!!!!
Thanks for letting me know. I have no idea what is causing that. I have triple checked my video rendering settings, and they all play fine for me locally and in all my browsers on my Windows machine (Edgeium and Chrome) as well as Chrome on my Android device. Have you tried a different browser? I have researched this and it seems to be browser/OS related.
@@GrahamStw Thanks for the feedback. I think I have this fixed in my latest videos. Can you watch one of my newer videos and let me know if you still see it?
What is the benefit of using tokens over simply using a bool field which is set when Cancel button is clicked and which is continuously checked in the loop?
You can pass it to Task.WaitAll and WhenAll. Also you can propagate the OperationCancelException over many child tasks. Most importantly it is thread safe. (A bool might be as well, but is also thread safe with all the other functionalities it provides)
ok, how to regenerate the token?? For example, when I press a button, I get ,,, and there are two "yes" or "no" buttons in it, if I click on the "no" button, then how to cancel the cancellation of the token, then what is the best way to do this ???
What if that "Long Running Operation" has some blocking part like listening UDP endpoint or pulling something? I cancel that token source but that worker thread is still running(waiting for that blocking synchronous operation to finish). Of course, we can just forget about that task - but it will read the next UDP message before the exception will be thrown and that message might be needed for me. Also, this situation consumes thread from the thread pool - instead of returning to the thread pool and be available to make some useful work - it just stays and waits for nothing. Is it possible to handle such kind of situation?
In my case I am waiting x seconds and if I abort it it needs to abort immediately and not after waiting for x seconds because I start the thread again with other values, so how do I do that without using a while loop that runs permanently using an entire cpu core for no reason at all and then still cancelling immdiately?
hi i have a question, i have a web application that schedules a backgroun job which is just a c# function , the problem is that the job executes every hour(this time is not set in stone it can variate depending on end user's desire) but there are some instances in which a new execution is about to begin and the previous one is not finished. I need to stop the previous execution before starting the new one which i cannot postpose , i have tryed to acomodate my code based on this video but i havne't been able to achieve this, can yo provide some advice ? i will really apreciate it
Did you get any solution for pause/resume, I am also looking for the same. As my process is long running, there is requirement to pause it in between. Thanks.
Great videos on C#, especially the async ones. Unfortunatelly I am not familiar with lambda expressions. Therefore ... is it posible for you to show the source code of the two videos "How to Report Progress with Async/Await in .NET Core 3" and "How to Cancel Tasks in C# - Using CancellationTokenSource and CancellationToken" in simple plain C# language with methods? That would be of great help for me. Thank You!
@@BrianLagunas Ok, basically you are right, so I deal with lambdas in the future, thank you! On the other hand, perhaps you can publish a video on lambdas?
Why everywhere I look, the demonstration is always about an easy loop where you can interrupt easily through cancellation token. I do not see people talk about a more sophisticated loop like where you have a bunch of tasks that doesn't last less than a second and you want to give them just a strict cut and run time out. If I use the cancellation token, if one of the task take too long for some reason, I can not cancel it right the way, I have to wait for that single task to finish before the cancel action take place. In this scenario, the cancellation token is useless, or close to useless if my user patience run-out. This is sometimes I think it is bad from a user perspective, when they expect the cancel button to work immediately. It doesn't happen and they just want to strangle the programmer,.... Why do I have to wait for my cancel? Isn't that's why I wanted to cancel in the first place? I don't want to wait.
Polling is probably the most popular approach to canceling tasks. Which is why you see so many videos on it. You can easily cancel a task based on a time limit though. It's actually much easier to cancel based on a time limit than using the polling approach. Just use CancellationTokenSource.CancelAfter. I hope that helps.
Great video. What would happen if i pass the Cancellation token directly to the Task.Run function. Does this also throw a operationcancelled exception?
I have a question, should i use asynchrony, if i need to run for example 40 tasks in parallel and then in each of 40 tasks run 5 more parallel task? Or threading or TPL should be used here?
I have been trying to make these code for 2 days. but the the exception has thrown and the program stopped I thought there is a problem becase I handled it. It turns out it's right. Thanks alot. I'm sorry about my English, I'm new learner
I'm not sure what you mean by stack unwinding, but as I mentioned in the video there are other ways to return from the task. You do not have to throw the exception.
Can you explain Thread.Abort() replacement in. net core with examples, if possible show with window forms using button on forms - start and stop. Windows form 1 Start button - thread.start() Stop button - thread.stop() Windows form 2 Start button - threads (pooled/start receiving external data) Stop button - thread cancellation token
Sir,I have a question. When I call method which creates collection inside user control loaded event, my combobox doesn't display any data. But if I call same method in viewmodel constructor, I get correct data in combo box. I observed that collection has data when I debug in loaded event, but is not displayed onto UI. Can you please help me or guide me in right direction 😊 How is loaded event different from calling in constructor? Thank you 😊
It's very hard to say. This points down to an issue in your implementation. It is possible your collection does not implement any type of change notifications. Use an ObservableCollection and chances are it will work.
When you call the cancellationtoken.dispose, what exactly does it do to the token, can you reuse it again? Im having issues where when i dispose it, redo the task and cancel it a second time, I get a error saying the token was disposed.
When you created token source in the class level , isn't that redundant : CancellationTokenSource _tokenSource = null. why you wrote " ... =null" . If we create a vairable without initiation then it will be null i.e. CancellationTokenSource _tokenSource; and that's it . And it is null so why you added " = null" ?
My question is how would you handle a cancel task if you have multiple thread running the same set of tests. In your example you have 4 different instances of the number collection happening, and each need to act completely independent from one another.
@@BrianLagunas I want to have system that does the same series of tests a multiple of times simultaneously. And i want to be abke to cancel each series individually. If i cancel one series, the remaining continue to run.
So each time a task is started, you want to store off the cancelation token. So for every time the task starts a new token is created. You can then choose which token to cancel from a list while the other tasks run. Does that sound right?
Most of the devs? Maybe most of the devs you know 😁. For these simple tutorials I want to keep the concept count down. Web is always complicated no matter what you do 🤣🤣🤣
4:30 You don't need the if on line 43; ThrowIfCancellationRequested will throw only if cancellation is requested and won't do anything otherwise. Love these videos. Keep'em coming!
Right, but I was showing how to poll the property, then do some cleanup. If you used just ThrowIf... there is no opportunity for clean up. Thanks for watching
You are a golden source to learn difficult stuffs to undersrand. Brilliant example and explanation.
You are too kind. Thank you so much.
Tip at 04:53 alone is gold! I was not aware of that detail. Thanks!! Nice short INFORMATIVE video!
Glad it was helpful!
Best async/await serie on youtube!!!!
Thank you so much
Small tip: in this code _tokenSource is null until the operation has been started, so pressing the Cancel button before you start the operation would cause a null-deref exception.
You can easily protect against that by using the Elvis-operator like this _tokenSource?.Cancel();
You should also set _tokenSource back to null after you Dispose it otherwise pressing the Cancel button twice would also cause errors as it would be calling Cancel on the disposed _tokenSource.
Right. This comes with the "demo code" disclaimer and does not represent production code 🤞
@@BrianLagunas Absolutely. Was more just a heads-up for the viewer that decides to copy-paste the whole thing to production. Because there is always one 😁
@@GrahamStw True that!
Loving these videos on async. Thanks for making the topic so approachable.
Thank you so much for watching
You deserve more subscription and views. Your videos are crystal clear and aweson. Great work.
I appreciate that!
I think the channels that have high numbers are more geared towards beginners. There are a few guys out there I know of that provide more advanced content, and they all seem to have the same "problem".
You have a point. Maybe I should start doing intro level topics 😁
Would love to see more of these videos on Tasks and threading cause the way you explain things are just simple and awesome! Keep the hard work :D
Sure, is there anything specific you would like to know?
Amazing video! Greatly explained!
Thank you so much
You saved me sir !! You're talented, keep it up!
From Morocco
Thank you so much. I'm happy I could help
Great video Brian! Clear and concise, thank you very much.
Thanks for watching
Just getting addicted to your videos 😍👌 the way you are explaining is awesome👌🙏
Just consider me your Tech Dealer 🤣
this is the solution I was looking for. Thanks
I’m glad this video was helpful. Thanks for watching
Great job explaining this, thank you. I like the approach you take with very simple blocks of code that get augmented with the cancellation part. Makes it more intuitive to follow along, much more than if you had started by showing the final code.
I appreciate the positive feedback. Thank you for watching and your support
Very nice video mate
Thank you
Great video! Very clear
Thanks for watching
Thank you for the awesome explaining :)
Thanks for watching
Thanks a lot Brian, this is amazing!
Thanks for watching
Thanks for the demo. Can you also demo something that has a "success token", to signal the completion of a long running task? Rather than using await to wait, the signal of the "success token" shall signal the completion of the task.
You can have something like this without the wait: Task.Run(() => gpl.StartTraceGathering( cts.Token)); and to stop it cts.Cancel() and cts.Dispose();
many thanks for your awesome tutorial
Thanks for watching
Nice and easy explination, Thanks!
Hi Brian. Thanks for this video. Can we have this cancellation token implemented for Background Service as well - can we cancel the task via UI screen ?
Awesome explanation. Simple and concise within an applicable context. I went to MS first and their explanations out of a practical context just made their documentation useless.
Thank you so much
Thank you Brian, you are my hero :-) these videos are so amazing
Thank you so much for the kind words
Extremely helpful thank you!
Thank you for watching
Nice and easy. Thanks!
Thanks for watching
Great videos!! I have in a script the following.
await Task.Run( async () => { MyFunction(); } );
and I want to cancel MyFunction after 2 seconds. How do I do that?
Don’t use Task.Run. Make your function an asynchrony function. Look into TaskCompletionSource
many thanks for the great content :) there still seems to be some audio sync issue (on windows 10 firefox), just wanted to make you aware as I read in a previous comment you were trying to fix it :) keep up the good work!!!!
Thanks for letting me know. I have no idea what is causing that. I have triple checked my video rendering settings, and they all play fine for me locally and in all my browsers on my Windows machine (Edgeium and Chrome) as well as Chrome on my Android device. Have you tried a different browser? I have researched this and it seems to be browser/OS related.
@@BrianLagunas Just a guess, is the audio constant bit rate, or variable?. I used to get lipsync issues on mp4 files using variable bit rate audio.
@@daverich3352 i just checked and it's a constant bit rate. Thanks for the idea though
@@BrianLagunas Audio is slightly out of sync for me too. On Win10 with latest Chrome (88.0.4324.190) playing the 1080p version.
@@GrahamStw Thanks for the feedback. I think I have this fixed in my latest videos. Can you watch one of my newer videos and let me know if you still see it?
What if i simply used boolean variable to indicate if i pressed the cancel button or not ? Is there any difference ?
Try it and see what happens
What is the benefit of using tokens over simply using a bool field which is set when Cancel button is clicked and which is continuously checked in the loop?
You can pass it to Task.WaitAll and WhenAll. Also you can propagate the OperationCancelException over many child tasks.
Most importantly it is thread safe. (A bool might be as well, but is also thread safe with all the other functionalities it provides)
ok, how to regenerate the token??
For example, when I press a button, I get ,,, and there are two "yes" or "no" buttons in it, if I click on the "no" button, then how to cancel the cancellation of the token, then what is the best way to do this ???
What if that "Long Running Operation" has some blocking part like listening UDP endpoint or pulling something? I cancel that token source but that worker thread is still running(waiting for that blocking synchronous operation to finish). Of course, we can just forget about that task - but it will read the next UDP message before the exception will be thrown and that message might be needed for me. Also, this situation consumes thread from the thread pool - instead of returning to the thread pool and be available to make some useful work - it just stays and waits for nothing. Is it possible to handle such kind of situation?
In my case I am waiting x seconds and if I abort it it needs to abort immediately and not after waiting for x seconds because I start the thread again with other values, so how do I do that without using a while loop that runs permanently using an entire cpu core for no reason at all and then still cancelling immdiately?
You can cancel a task after a period of time using the CancellationTokenSource.CancelAfter(YourValue)
WOW! this video is very helpful and useful.
I wish that the code is also available - Thank you. Thumbs Up!
Thank you so much for watching
hi i have a question, i have a web application that schedules a backgroun job which is just a c# function , the problem is that the job executes every hour(this time is not set in stone it can variate depending on end user's desire) but there are some instances in which a new execution is about to begin and the previous one is not finished. I need to stop the previous execution before starting the new one which i cannot postpose , i have tryed to acomodate my code based on this video but i havne't been able to achieve this, can yo provide some advice ? i will really apreciate it
Brian, really good. I would also like to know how to, instead of throwing an exception, actually allow the user to pause and/or resume.
I'm not sure. I've never had to pause a task before.
Did you get any solution for pause/resume, I am also looking for the same. As my process is long running, there is requirement to pause it in between. Thanks.
How is this done if a task that needs to be run does not involve a for loop?
Great videos on C#, especially the async ones. Unfortunatelly I am not familiar with lambda expressions.
Therefore ... is it posible for you to show the source code of the two videos "How to Report Progress with Async/Await in .NET Core 3" and "How to Cancel Tasks in C# - Using CancellationTokenSource and CancellationToken" in simple plain C# language with methods? That would be of great help for me. Thank You!
Honestly, you're probably better off learning how to use lambdas than to stick with the old ways of doing things. Maybe I will do a video on lambdas
@@BrianLagunas Ok, basically you are right, so I deal with lambdas in the future, thank you! On the other hand, perhaps you can publish a video on lambdas?
Yeah, that might be a good one
What if I don’t/can’t use polling? Like a db task which may take too long n I just want to timeout?
Why everywhere I look, the demonstration is always about an easy loop where you can interrupt easily through cancellation token. I do not see people talk about a more sophisticated loop like where you have a bunch of tasks that doesn't last less than a second and you want to give them just a strict cut and run time out. If I use the cancellation token, if one of the task take too long for some reason, I can not cancel it right the way, I have to wait for that single task to finish before the cancel action take place. In this scenario, the cancellation token is useless, or close to useless if my user patience run-out. This is sometimes I think it is bad from a user perspective, when they expect the cancel button to work immediately. It doesn't happen and they just want to strangle the programmer,.... Why do I have to wait for my cancel? Isn't that's why I wanted to cancel in the first place? I don't want to wait.
Polling is probably the most popular approach to canceling tasks. Which is why you see so many videos on it. You can easily cancel a task based on a time limit though. It's actually much easier to cancel based on a time limit than using the polling approach. Just use CancellationTokenSource.CancelAfter. I hope that helps.
@@BrianLagunas That approach of cancelAfter won't work for running task
That cleared many things 😊
Great to hear. Thanks for watching
You just handled exception in async void, can click event handle it even in async void? 😱 That's Magical
Thanks for watching
nice explanation
Thank you
Great video. What would happen if i pass the Cancellation token directly to the Task.Run function. Does this also throw a operationcancelled exception?
No, it does not. It appears to do nothing.
I have a question, should i use asynchrony, if i need to run for example 40 tasks in parallel and then in each of 40 tasks run 5 more parallel task? Or threading or TPL should be used here?
Sounds over complicated. I think this could be greatly simplified
Greate video, except that token.ThrowIfCancellationRequested(); always stops the application and does not call the catch in which task was running.
How do you cancel task in a .NET Core application?
I have been trying to make these code for 2 days. but the the exception has thrown and the program stopped I thought there is a problem becase I handled it. It turns out it's right. Thanks alot. I'm sorry about my English, I'm new learner
Would the stack unwinding take place cause of the exception? Is there another way to return from the task?
I'm not sure what you mean by stack unwinding, but as I mentioned in the video there are other ways to return from the task. You do not have to throw the exception.
Can you explain Thread.Abort() replacement in. net core with examples, if possible show with window forms using button on forms - start and stop.
Windows form 1
Start button - thread.start()
Stop button - thread.stop()
Windows form 2
Start button - threads (pooled/start receiving external data)
Stop button - thread cancellation token
Wow that was concise, one question how do we cancel an API task we are running on the backend ?
I'm pretty sure you just need to create a CancellationToeknSource and pass the token to the HttpClient.GetAsync method.
How to use Continuation Token in C# for rest API calls?
Hello Can you please make a video on some of best practices you follow in developing WPF applications ☺️
Thank you
Sure. I may have to break them up into separate videos because there are so many 😁
@@BrianLagunas yes that's what I planned to request but didn't mention in comment 😃.
A mini series with best practices would be helpful :)
Thank you
What if the task is actually from another third party class that we can't check the token.IsCancellationRequested?
Are asking how to cancel a task you don't own and didn't write?
@@BrianLagunas Yes sir. That's exactly what I meant.
You can't cancel non-cancelable operations
Sir,I have a question. When I call method which creates collection inside user control loaded event, my combobox doesn't display any data. But if I call same method in viewmodel constructor, I get correct data in combo box. I observed that collection has data when I debug in loaded event, but is not displayed onto UI.
Can you please help me or guide me in right direction 😊
How is loaded event different from calling in constructor?
Thank you 😊
It's very hard to say. This points down to an issue in your implementation. It is possible your collection does not implement any type of change notifications. Use an ObservableCollection and chances are it will work.
When you call the cancellationtoken.dispose, what exactly does it do to the token, can you reuse it again? Im having issues where when i dispose it, redo the task and cancel it a second time, I get a error saying the token was disposed.
No. Once you dispose of the token you cannot use it again. You must create a new one and dispose it when you’re done with it.
@@BrianLagunas gotcha. It turned out to be a bug unrelated to the tokens. Thanks for the video tho, short and very helpful 🙌
How to implement pause/resume functionality using task?
Hmmm... that would be a fun one
@@BrianLagunas sir please show it. It should be a fun one and interesting to pause and resume.
When you created token source in the class level , isn't that redundant : CancellationTokenSource _tokenSource = null. why you wrote " ... =null" . If we create a vairable without initiation then it will be null i.e. CancellationTokenSource _tokenSource; and that's it . And it is null so why you added " = null" ?
I always initialize my variables to make their values explicit.
Thank you 😊😊
You are welcome sir
My question is how would you handle a cancel task if you have multiple thread running the same set of tests. In your example you have 4 different instances of the number collection happening, and each need to act completely independent from one another.
So you want to cancel multiple tasks at the same time?
@@BrianLagunas I want to have system that does the same series of tests a multiple of times simultaneously. And i want to be abke to cancel each series individually. If i cancel one series, the remaining continue to run.
So each time a task is started, you want to store off the cancelation token. So for every time the task starts a new token is created. You can then choose which token to cancel from a list while the other tasks run. Does that sound right?
@@BrianLagunas so create a list/array of tokens and associate each element to a series?
Possibly. I'm just trying to understand the scenario and thinking through how I might do it
Grats!
Thanks
What if they clicked the "Loop Through Numbers" button multiple times? How would you stop that?
There are a number of way to do this, but the easiest would be to just disable the button until the operation is complete.
The audio/video sync is enough to make me want to cancel this task!
Thank you!
Thank you for watching
Thank you
Thanks for watching
Content starts at 1:35
Thanks for the time stamp
roll dat intro!
good one!!👍👍
Request to use proper api and web ui projects for these tutorials as most of the the devs follow api -> json -> webUI
Most of the devs? Maybe most of the devs you know 😁. For these simple tutorials I want to keep the concept count down. Web is always complicated no matter what you do 🤣🤣🤣
@@BrianLagunas Yes.. most of the devs I know are involved in web development
Wunderbar