DEV Community

Cancellation Tokens in C#

Rasheed K Mozaffar on June 11, 2024

Hi There! 👋🏻 It's been a while since I wrote something about C#, or wrote anything in general, but now I have an interesting concept tha...
Collapse
 
parentelement profile image
Dustin Horne (parentelement)

Good primer. I read this as someone who already knows and uses cancellationTokens (the way it was intended, not just default value and ignoring). One thing I'd recommend adding to this is an example and using linked sources through CancellationTokenSource.CreateLinkedTokenSource(...). This is where cancellation tokens get really powerful because you then get your own token that you can use and cancellation can be reacted to wether it's the original token or yours. I use this technique in my ParentElement.ReProcess package (source is on GitHub).

Collapse
 
rasheedmozaffar profile image
Rasheed K Mozaffar

Tysm for mentioning that!
I was thinking of making a sequel to this post where I delve into more details and code samples, so I'll definitely come back to your recommendation!

Collapse
 
rumendimov profile image
Rumen Dimov • Edited

I have used CacellationTokens when running BackgroundService tasks. But I never thought about using them with EF core retrieving data as shown in the example.

Awesome content!

Collapse
 
krakoss profile image
krakoss

this is very useful information

Collapse
 
1hamzabek profile image
Hamza

It is great!!

Collapse
 
fredrikskne profile image
Fredrik Karlsson

Why are you mixing Thread.Sleep and async/await?

Collapse
 
rasheedmozaffar profile image
Rasheed K Mozaffar

Thanks for pointing that out!

Collapse
 
pinaki_basu_27d0350c46cdf profile image
Pinaki Basu

learned something which could be useful!

Collapse
 
chung_ontsui_c76da0625d0 profile image
Chung On Tsui

Good article on a topic probably not considered often enough, good job 👍🏻

Collapse
 
rasheedmozaffar profile image
Rasheed K Mozaffar

Thank you! Glad you liked it

Collapse
 
tablepad profile image
Tablepad

Awensome post!

Collapse
 
adn_ng_5d75dafc2f4b7f531f profile image
Adn Ng

thank you

Collapse
 
rasheedmozaffar profile image
Rasheed K Mozaffar

Glad that was useful 😁

Collapse
 
anandhu_uthaman_015e31bce profile image
Anandhu Uthaman

It's very useful

Collapse
 
softwaredeveloping profile image
FrontEndWebDeveloping

Hey Rasheed! How is Flow going? Have you finished your second version?

Collapse
 
rasheedmozaffar profile image
Rasheed K Mozaffar

Hey mate!
Uhh unfortunately i couldn't proceed with the development, I got swamped with some freelance work, college assignments and I'm preparing to start my new job next month, so I had to stop working on Flow, i dunno if I'll get back to it later or not, but I'm sure once everything settles, I'll find some time to continue working on it!

Collapse
 
softwaredeveloping profile image
FrontEndWebDeveloping

Okay... sounds good. Thanks Rasheed.