How Do You Cancel an async Method? | Step-by-Step Tutorial

How Do You Cancel an async Method? | Step-by-Step Tutorial

Zoran Horvat

5 месяцев назад

7,190 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

@HELLOBOYZ-c6o
@HELLOBOYZ-c6o - 15.04.2024 11:05

Another high quality video for real world projects. Thank you so much!

Ответить
@mcstonesen
@mcstonesen - 15.04.2024 11:21

Nice video. I always love to see your well explained scenarios, which make it easier to get the point of each topic. Btw. was the voice in this video AI generated? Every word was so uniformly pronounced, that I started to feel a little uncomfortable 😂

Ответить
@codingbloke
@codingbloke - 15.04.2024 11:39

Another great video. I'd like to know more about this functional pattern which leads to the CancelationToken being passed first in the parameter list. So far I have followed the pattern of existing libraries of having the CancellationToken be an optional parameter at the end of the parameter list. Perhaps this is a subject of another video?

Ответить
@gligom
@gligom - 15.04.2024 12:34

Every time i watch your videos my head 🤯. I know, your speed and advanced understanding of all this concepts comes after many years of experience. Even with this headache I still watch and enjoy every minute, hopping that one day I will understand too…

Ответить
@spechulfapticks3108
@spechulfapticks3108 - 15.04.2024 13:04

i will not judge you if you judge me for making cancellation token be 1-st parameter ©

Ответить
@HOSTRASOKYRA
@HOSTRASOKYRA - 15.04.2024 13:19

Thank you very much for this so helpful video!

Ответить
@escribe6751
@escribe6751 - 15.04.2024 13:50

What does BCL stand for?

Ответить
@billy65bob
@billy65bob - 15.04.2024 16:09

Every single one of my async methods tends to end with `CancellationToken token = default`, which makes the token optional.
I'm really not a fan of exceptions at the best of times, but the exceptions around Tasks really annoy me.
Just consider that some spots throw OperationCancelledException, then others do TaskCancelledException, and just to make it more annoying, there's also a SqlException with the message "Operation was cancelled by the user"... Not a fan.

Ответить
@AKW91
@AKW91 - 15.04.2024 17:00

The CancellationTokenSource should be created in a using statement, since it implements IDisposable. Although I believe it doesn't matter as long as no one uses the internal WaitHandle or starts a cancellation timer.

Ответить
@MC_DarkMaster
@MC_DarkMaster - 15.04.2024 19:39

I hate that the try/catch-syntax needs so much unnecessary boilerplate lines

Ответить
@jamesbond6761
@jamesbond6761 - 15.04.2024 23:05

Why did you not dispose of CancellationTokenSource? It might lead to a memory leak.

Ответить
@baranacikgoz
@baranacikgoz - 16.04.2024 00:10

I guess we can yield progress with IAsyncEnumarable

Ответить
@hozmannew896
@hozmannew896 - 16.04.2024 01:03

well explained concepts, thank you

Ответить
@pferreirafabricio
@pferreirafabricio - 16.04.2024 01:37

First of all, thank you for this high-quality content!

I tried to implement similar code using the final adjustments that you made, but I got stuck in the scenario where the user decide to wait for the total file to be generated, the process never ends, the message "Ended interaction." is never displayed.

After some research I found some StackOverflow questions talking about how "while (!fileWriter.IsCompleted)" was causing a dead lock.

Is this the scenario? Is the main thread waiting for the task to complete, and is the task waiting for the main thread to be free to run the continuation?

Ответить
@leos-clockworks335
@leos-clockworks335 - 16.04.2024 08:13

Async tasks bring quite a lot of power, and I'd even say are needed in every project.
I also like using TaskCompletionSource as there are some good use cases for it, when your project starts doing more complex calls between services.

Ответить
@dwhxyz
@dwhxyz - 17.04.2024 12:54

It should be noted that there are times when a developer will need to gracefully handle the entire cancellation logic themselves. This could include letting some/all parts of an operation complete (and in turn selectively passing down the cancellation token to in-built .NET framework methods) and/or undoing/cleaning up some parts of an operation that is being cancelled depending on how far it got when the cancellation was triggered. Just blindly passing down the cancelled token to everything in the chain (from say an API/MVC web request) could leads to serious issues in some application and hence in many instances (especially if the operation is short lived) it would be better/safer to just to let the operation complete without passing down the cancellation token to anything! Unfortunately all the videos I see on this subject don't really address the entire cancellation subject and just focus on the cancellation source/token.

Ответить
@RualddeBruyn
@RualddeBruyn - 19.04.2024 12:20

Thanks!

Ответить
@XtroTheArctic
@XtroTheArctic - 19.04.2024 19:21

Hi Zoran. I was reading the MS documentation about CancellationToken yesterday and today I saw your video. I need to ask, wouldn't it be better to create a linked token in GenerateTextFile task for passing to WriteAsync, instead of passing the same token to it? If not, can you explain the purpose of the linked token? I thought this was its purpose.

And one more thing. Would it be problematic if my task doesn't throw cancelled exception and simply return instead. The caller can check CancellationToken.IsCancellationRequested too to learn about cancellation, instead of relying on the exception from the task. That's how I implemented my system yesterday. Would it be much preferable doing it the exception way, and why?

Thank you very much.

Ответить
@7th_CAV_Trooper
@7th_CAV_Trooper - 23.04.2024 04:10

Why does adding the cancelation token as the first argument help with functional programming? Do I need to go read up on FCL?

Don't forget to dispose the CancelationTokenSource.

If you get an IO exception during the Delete operation just turn your computer off and call it a day.
 
Note to self: BCL has nothing to do with the Borland Class Library which was never actually a thing.

Ответить
@tore28
@tore28 - 14.07.2024 00:33

This example was fun to follow along, it is easier to test out if you at least generate a file 5-10 MB in size if you want to test out yourself, so it takes some time to write those randomized letters with the 128 byte buffer.

When will the use of CreatedLinkedTokenSource be relevant in C# ? It would be nice with a follow up video on that topic.

Ответить