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

Поделиться
HTML-код
  • Опубликовано: 29 дек 2024

Комментарии • 151

  • @DanielLiuzzi
    @DanielLiuzzi 4 года назад +11

    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!

    • @BrianLagunas
      @BrianLagunas  4 года назад +12

      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

  • @kopilkaiser8991
    @kopilkaiser8991 Год назад +2

    You are a golden source to learn difficult stuffs to undersrand. Brilliant example and explanation.

    • @BrianLagunas
      @BrianLagunas  Год назад

      You are too kind. Thank you so much.

  • @pearsonkevin4699
    @pearsonkevin4699 4 года назад +1

    Tip at 04:53 alone is gold! I was not aware of that detail. Thanks!! Nice short INFORMATIVE video!

  • @longuinni
    @longuinni 4 года назад +2

    Best async/await serie on youtube!!!!

  • @GrahamStw
    @GrahamStw 3 года назад +10

    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
      @BrianLagunas  3 года назад +4

      Right. This comes with the "demo code" disclaimer and does not represent production code 🤞

    • @GrahamStw
      @GrahamStw 3 года назад +3

      @@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 😁

    • @BrianLagunas
      @BrianLagunas  3 года назад +1

      @@GrahamStw True that!

  • @mattn-mn
    @mattn-mn 4 года назад +4

    Loving these videos on async. Thanks for making the topic so approachable.

    • @BrianLagunas
      @BrianLagunas  4 года назад +1

      Thank you so much for watching

  • @ibknl1986
    @ibknl1986 4 года назад +4

    You deserve more subscription and views. Your videos are crystal clear and aweson. Great work.

    • @BrianLagunas
      @BrianLagunas  4 года назад

      I appreciate that!

    • @ronaldmackee3401
      @ronaldmackee3401 3 года назад +1

      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".

    • @BrianLagunas
      @BrianLagunas  3 года назад

      You have a point. Maybe I should start doing intro level topics 😁

  • @BochraBouazizi
    @BochraBouazizi 4 года назад +5

    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

    • @BrianLagunas
      @BrianLagunas  4 года назад

      Sure, is there anything specific you would like to know?

  • @dariorud
    @dariorud Год назад +1

    Amazing video! Greatly explained!

  • @MDIVINN
    @MDIVINN 4 года назад +2

    You saved me sir !! You're talented, keep it up!
    From Morocco

    • @BrianLagunas
      @BrianLagunas  4 года назад

      Thank you so much. I'm happy I could help

  • @samueldrysen4983
    @samueldrysen4983 3 года назад +1

    Great video Brian! Clear and concise, thank you very much.

  • @udaysuddhala3512
    @udaysuddhala3512 4 года назад +3

    Just getting addicted to your videos 😍👌 the way you are explaining is awesome👌🙏

    • @BrianLagunas
      @BrianLagunas  4 года назад

      Just consider me your Tech Dealer 🤣

  • @jcjensenllc
    @jcjensenllc Год назад +1

    this is the solution I was looking for. Thanks

    • @BrianLagunas
      @BrianLagunas  Год назад

      I’m glad this video was helpful. Thanks for watching

  • @boysen01
    @boysen01 2 года назад +1

    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.

    • @BrianLagunas
      @BrianLagunas  2 года назад

      I appreciate the positive feedback. Thank you for watching and your support

  • @Yo-nd8xj
    @Yo-nd8xj 2 года назад +1

    Very nice video mate

  • @paolocantore7641
    @paolocantore7641 2 года назад +1

    Great video! Very clear

  • @hashiii08
    @hashiii08 2 года назад +1

    Thank you for the awesome explaining :)

  • @reyou7
    @reyou7 Год назад +1

    Thanks a lot Brian, this is amazing!

  • @daixtr
    @daixtr 2 года назад +1

    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.

    • @atilathesonofdanubius4277
      @atilathesonofdanubius4277 2 года назад

      You can have something like this without the wait: Task.Run(() => gpl.StartTraceGathering( cts.Token)); and to stop it cts.Cancel() and cts.Dispose();

  • @solvedplus858
    @solvedplus858 4 года назад +1

    many thanks for your awesome tutorial

  • @myWorldDiscover
    @myWorldDiscover 11 месяцев назад

    Nice and easy explination, Thanks!

  • @hassan.sadeed.ali.08
    @hassan.sadeed.ali.08 5 месяцев назад

    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 ?

  • @atilathesonofdanubius4277
    @atilathesonofdanubius4277 2 года назад +1

    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.

  • @julianturner6203
    @julianturner6203 4 года назад +1

    Thank you Brian, you are my hero :-) these videos are so amazing

    • @BrianLagunas
      @BrianLagunas  4 года назад

      Thank you so much for the kind words

  • @joshdavis9201
    @joshdavis9201 Год назад +1

    Extremely helpful thank you!

  • @unsignedbyte
    @unsignedbyte 3 года назад +1

    Nice and easy. Thanks!

  • @ingjn7858
    @ingjn7858 Год назад +1

    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?

    • @BrianLagunas
      @BrianLagunas  Год назад

      Don’t use Task.Run. Make your function an asynchrony function. Look into TaskCompletionSource

  • @johanneslaute3675
    @johanneslaute3675 4 года назад +3

    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!!!!

    • @BrianLagunas
      @BrianLagunas  4 года назад +1

      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.

    • @daverich3352
      @daverich3352 4 года назад

      @@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.

    • @BrianLagunas
      @BrianLagunas  4 года назад

      @@daverich3352 i just checked and it's a constant bit rate. Thanks for the idea though

    • @GrahamStw
      @GrahamStw 3 года назад +1

      @@BrianLagunas Audio is slightly out of sync for me too. On Win10 with latest Chrome (88.0.4324.190) playing the 1080p version.

    • @BrianLagunas
      @BrianLagunas  3 года назад

      @@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?

  • @emad-dev
    @emad-dev 2 года назад +1

    What if i simply used boolean variable to indicate if i pressed the cancel button or not ? Is there any difference ?

  • @paulp4061
    @paulp4061 2 года назад +1

    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?

    • @lavatasche2806
      @lavatasche2806 Год назад +1

      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)

  • @hatoryhanzo238
    @hatoryhanzo238 2 года назад

    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 ???

  • @TedFanat
    @TedFanat 3 года назад

    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?

  • @maffin7228
    @maffin7228 3 года назад +1

    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?

    • @BrianLagunas
      @BrianLagunas  3 года назад

      You can cancel a task after a period of time using the CancellationTokenSource.CancelAfter(YourValue)

  • @judyrheanebangcaya1472
    @judyrheanebangcaya1472 2 года назад +1

    WOW! this video is very helpful and useful.
    I wish that the code is also available - Thank you. Thumbs Up!

  • @randomUser2121
    @randomUser2121 4 года назад

    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

  • @dannybradley9346
    @dannybradley9346 3 года назад

    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.

    • @BrianLagunas
      @BrianLagunas  3 года назад

      I'm not sure. I've never had to pause a task before.

    • @mayurbanta
      @mayurbanta 3 года назад

      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.

  • @TinoCav
    @TinoCav 3 года назад

    How is this done if a task that needs to be run does not involve a for loop?

  • @os-channel
    @os-channel 4 года назад

    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
      @BrianLagunas  4 года назад +1

      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

    • @os-channel
      @os-channel 4 года назад

      @@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?

    • @BrianLagunas
      @BrianLagunas  4 года назад

      Yeah, that might be a good one

  • @expertreviews1112
    @expertreviews1112 10 месяцев назад

    What if I don’t/can’t use polling? Like a db task which may take too long n I just want to timeout?

  • @medusaskull1604
    @medusaskull1604 4 года назад +1

    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.

    • @BrianLagunas
      @BrianLagunas  4 года назад +1

      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.

    • @AbbiB-r7o
      @AbbiB-r7o 10 месяцев назад

      @@BrianLagunas That approach of cancelAfter won't work for running task

  • @tusharparab9866
    @tusharparab9866 4 года назад +1

    That cleared many things 😊

    • @BrianLagunas
      @BrianLagunas  4 года назад

      Great to hear. Thanks for watching

  • @_samirdahal
    @_samirdahal 4 года назад +1

    You just handled exception in async void, can click event handle it even in async void? 😱 That's Magical

  • @satyad833
    @satyad833 4 года назад +1

    nice explanation

  • @MrBan001
    @MrBan001 4 года назад

    Great video. What would happen if i pass the Cancellation token directly to the Task.Run function. Does this also throw a operationcancelled exception?

    • @BrianLagunas
      @BrianLagunas  4 года назад

      No, it does not. It appears to do nothing.

  • @ВладимирКремлев-у2ь

    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?

    • @BrianLagunas
      @BrianLagunas  3 года назад

      Sounds over complicated. I think this could be greatly simplified

  • @alrajhi
    @alrajhi 2 года назад

    Greate video, except that token.ThrowIfCancellationRequested(); always stops the application and does not call the catch in which task was running.

  • @cmtv357
    @cmtv357 2 года назад

    How do you cancel task in a .NET Core application?

  • @SherifAli-xx7xt
    @SherifAli-xx7xt 11 месяцев назад

    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

  • @deepak20002075
    @deepak20002075 4 года назад

    Would the stack unwinding take place cause of the exception? Is there another way to return from the task?

    • @BrianLagunas
      @BrianLagunas  4 года назад

      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.

  • @AnupDhate
    @AnupDhate 2 года назад

    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

  • @KunalMukherjee3701
    @KunalMukherjee3701 3 года назад

    Wow that was concise, one question how do we cancel an API task we are running on the backend ?

    • @BrianLagunas
      @BrianLagunas  3 года назад +1

      I'm pretty sure you just need to create a CancellationToeknSource and pass the token to the HttpClient.GetAsync method.

  • @shwetak925
    @shwetak925 2 года назад

    How to use Continuation Token in C# for rest API calls?

  • @VinuP2023
    @VinuP2023 4 года назад +1

    Hello Can you please make a video on some of best practices you follow in developing WPF applications ☺️
    Thank you

    • @BrianLagunas
      @BrianLagunas  4 года назад +1

      Sure. I may have to break them up into separate videos because there are so many 😁

    • @VinuP2023
      @VinuP2023 4 года назад +1

      @@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

  • @samsman007
    @samsman007 4 года назад

    What if the task is actually from another third party class that we can't check the token.IsCancellationRequested?

    • @BrianLagunas
      @BrianLagunas  4 года назад

      Are asking how to cancel a task you don't own and didn't write?

    • @samsman007
      @samsman007 4 года назад

      @@BrianLagunas Yes sir. That's exactly what I meant.

    • @BrianLagunas
      @BrianLagunas  4 года назад

      You can't cancel non-cancelable operations

  • @VinuP2023
    @VinuP2023 4 года назад

    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 😊

    • @BrianLagunas
      @BrianLagunas  4 года назад +1

      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.

  • @somerandomguywastaken
    @somerandomguywastaken 2 года назад

    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.

    • @BrianLagunas
      @BrianLagunas  2 года назад

      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.

    • @somerandomguywastaken
      @somerandomguywastaken 2 года назад +1

      @@BrianLagunas gotcha. It turned out to be a bug unrelated to the tokens. Thanks for the video tho, short and very helpful 🙌

  • @harsheng
    @harsheng 4 года назад +1

    How to implement pause/resume functionality using task?

    • @BrianLagunas
      @BrianLagunas  4 года назад +4

      Hmmm... that would be a fun one

    • @VinuP2023
      @VinuP2023 4 года назад +1

      @@BrianLagunas sir please show it. It should be a fun one and interesting to pause and resume.

  • @kalka79
    @kalka79 3 года назад

    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" ?

    • @BrianLagunas
      @BrianLagunas  3 года назад +1

      I always initialize my variables to make their values explicit.

  • @VinuP2023
    @VinuP2023 4 года назад +1

    Thank you 😊😊

  • @crimsonvance839
    @crimsonvance839 4 года назад

    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
      @BrianLagunas  4 года назад

      So you want to cancel multiple tasks at the same time?

    • @crimsonvance839
      @crimsonvance839 4 года назад

      @@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.

    • @BrianLagunas
      @BrianLagunas  4 года назад

      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?

    • @crimsonvance839
      @crimsonvance839 4 года назад

      @@BrianLagunas so create a list/array of tokens and associate each element to a series?

    • @BrianLagunas
      @BrianLagunas  4 года назад

      Possibly. I'm just trying to understand the scenario and thinking through how I might do it

  • @simonaugusto
    @simonaugusto 3 года назад +1

    Grats!

  • @Anequit
    @Anequit 3 года назад

    What if they clicked the "Loop Through Numbers" button multiple times? How would you stop that?

    • @BrianLagunas
      @BrianLagunas  3 года назад

      There are a number of way to do this, but the easiest would be to just disable the button until the operation is complete.

  • @DConnor799
    @DConnor799 2 года назад

    The audio/video sync is enough to make me want to cancel this task!

  • @eugene00777
    @eugene00777 4 года назад +1

    Thank you!

  • @NAEL4SLR
    @NAEL4SLR 2 года назад +1

    Thank you

  • @MarkJones
    @MarkJones 3 года назад

    Content starts at 1:35

  • @user-mr-m12312
    @user-mr-m12312 4 года назад +2

    roll dat intro!

  • @IndiaThatIsBhaarat
    @IndiaThatIsBhaarat 4 года назад

    good one!!👍👍
    Request to use proper api and web ui projects for these tutorials as most of the the devs follow api -> json -> webUI

    • @BrianLagunas
      @BrianLagunas  4 года назад +1

      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 🤣🤣🤣

    • @IndiaThatIsBhaarat
      @IndiaThatIsBhaarat 3 года назад

      @@BrianLagunas Yes.. most of the devs I know are involved in web development

  • @yippeeki-yey
    @yippeeki-yey 3 года назад

    Wunderbar