Semaphore Explained C#

In this Semaphore tutorial, I answer the questions: what is semaphore? what is semaphore used for? how to use semaphore? We go over a quick analogy to understand what the semaphore does and how to use it. We then look at a real world example of how it can be used to solve problems caused by asynchronous programming.
Patreon 🤝 / raw_coding
Courses 📚 learning.raw-coding.dev
Shop 🛒 shop.raw-coding.dev
Discord 💬 / discord
Twitter 📣 / anton_t0shik
Twitch 🎥 / raw_coding
👉 Try Rider
www.jetbrains.com/store/redeem/
RD5K9-4TXXW-KMV3G-NYWSF-3ZSTP
Source: github.com/T0shik/raw-coding-...
#csharp

Пікірлер: 156

  • @MiTaReX
    @MiTaReX Жыл бұрын

    Thanks for the tutorial! One note: when talking about semaphores, I think you missed the intended metaphor. Semaphore means "apparatus for signaling" and in this context it means railway semaphores, which you can think of "traffic lights for trains". There are two states for a railway semaphore: open and closed, so this is the intentional metaphor for the naming, it functions the same as your "gate" idea. =)

  • @RawCoding

    @RawCoding

    Жыл бұрын

    thank you, I didn't know

  • @BrendonParker
    @BrendonParker3 жыл бұрын

    Great tutorial, thanks! I imagine you’d want to move the release of the Semaphore to a “finally” block, otherwise those “gates” are permanently closed on an exception.

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Yes, thank you for pointing out. :)

  • @Gmaniacuk1
    @Gmaniacuk13 жыл бұрын

    Fantastically simple explanation, with both Hello World and real world examples. Short, sweet and simple - thank you.

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Glad you liked it!

  • @salamioluwapelumi
    @salamioluwapelumi4 жыл бұрын

    This channels needs more than a million subscribers ; wish i could subscribe a million times

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Haha thanks man, we’ll get there ;)

  • @dougstanley8942
    @dougstanley89429 ай бұрын

    Well done young man - great stuff, and no edits. Impressive

  • @sadhat75
    @sadhat753 жыл бұрын

    Best semaphore tutorial ever! I always struggled to understand it. After watching this, its crystal clear now! Thank you! The only thing I need to remember is the magic word - (Bill) GATEs!!!

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Haha glad I could help :)

  • @ahmedlshubaky7336
    @ahmedlshubaky73362 жыл бұрын

    thx from egypt, u saved my project because previously i was using deprecated thread methods such : suspend and resume which are have a lot of issues and not working properly. thx again

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    Glad to hear!

  • @nuevoaioria
    @nuevoaioria2 жыл бұрын

    My God!! You are the man!!! I had tried with many videos,codes,etc. Until I see your video and I did it succesfully in my first attempt!! Thank u man!!

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    Glad to hear )

  • @mrjamiebowman1337
    @mrjamiebowman13373 жыл бұрын

    This is excellent. A great way of explaining this. I struggled to understand Semaphores until now

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Glad you like it )

  • @NillKitty
    @NillKitty4 жыл бұрын

    It's not that your network card is too slow to connect to Google 200 times at once, it's that your TCP/IP stack (and Google's too) has a set limit on how many unestablished connections can be buffered at once. In effect you're seeing this because Windows has its own "gate" and your socket requests start to block. The reason for this is to avoid allocating huge amounts of RAM to the TCP/IP driver in the event a program is stuck in a tight loop trying and failing to connect to something. Your actual NIC driver only knows about frames, not socket connections, and can blast data at upwards of 10Gbps. You're using HttpClient so the back-up may even be one layer higher (in http.sys) rather than in the native TCP stack itself.

  • @NillKitty

    @NillKitty

    4 жыл бұрын

    Also you have 65535 theoretical TCP ports so you're also not running out of that.

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    I’ll take your word for it :D

  • @LucasMarinoElementh
    @LucasMarinoElementh4 жыл бұрын

    Thank you for the video. It is always nice to revisit some knowledge when you don't use it fairly often.

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Thank you for watching))

  • @taraspelenio8259
    @taraspelenio82594 жыл бұрын

    Good and brief description. Excellent work. I like such format.

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Cheers )

  • @aliveGR
    @aliveGR4 жыл бұрын

    Great tutorial! Thank you for taking the time to explain this so well.

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Thank you for watching

  • @enesyapmaz7053
    @enesyapmaz70534 жыл бұрын

    Explains and sample are so good. Thanks for everything

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Cheers :)

  • @iliyanangelov
    @iliyanangelov4 жыл бұрын

    Amazing video! Short, clean to the point. Subscribed :)

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Glad you liked it!

  • @guillermoarroyo9465
    @guillermoarroyo94654 жыл бұрын

    Excellent, just what I needed. Great job

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Glad I could help

  • @mohdnasir7023
    @mohdnasir70232 жыл бұрын

    Finally the tutorial which resolved my issue. Thanks man😊

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    Thank you for watching

  • @Vptkvc
    @Vptkvc4 жыл бұрын

    very concise and well explained! thanks brother!

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Cheers))

  • @user-rv8tq7vk2f
    @user-rv8tq7vk2f4 жыл бұрын

    Great tutorial. Thanks a lot!

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Cheers )

  • @poornimanayar8647
    @poornimanayar86473 жыл бұрын

    Really love your videos! Very informative and well explained

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Thank you for watching :)

  • @seccisec
    @seccisec4 жыл бұрын

    Nice little video :) Thx for sharing.

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Cheers

  • @kopilkaiser8991
    @kopilkaiser8991 Жыл бұрын

    Awesome tutorial. I've now a better understanding about this topic Thank you for your hard work and effort. I can see you enjoy teaching and I really enjoy learning. I hope to be as intelligent as you are and understand c# logic as the way you understand.

  • @HoangIT21
    @HoangIT213 жыл бұрын

    Thanks for sharing! Great video. Thanks bro!

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Thank you for watching;)

  • @LetsLearnWithA.R
    @LetsLearnWithA.R3 жыл бұрын

    Great tutorial !!!! Thanks buddy !!!

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Thank you for watching)

  • @KrishnaList
    @KrishnaList4 жыл бұрын

    Anton fantastic explanation👍🏼👍🏼👍🏼👍🏼

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Thank you ))

  • @raghavendransrinivasan7496
    @raghavendransrinivasan7496 Жыл бұрын

    Clear explanation, thanks.

  • @RawCoding

    @RawCoding

    Жыл бұрын

    Thank you for watching!

  • @ayoubdkhissi
    @ayoubdkhissi Жыл бұрын

    Great explanation, the http requests example was very accurate

  • @squidward66
    @squidward662 жыл бұрын

    nice clear explanation and demo

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    Cheers

  • @rajas7841
    @rajas78414 жыл бұрын

    Nice explanation 👌

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Cheers

  • @rgbetanco604
    @rgbetanco6043 жыл бұрын

    Thanks, highly appreciated

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Cheers

  • @anatoliytkachenko1498
    @anatoliytkachenko14983 жыл бұрын

    Thank you for the clarification. Like!

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Thank you for watching

  • @dhanyajoy7043
    @dhanyajoy7043 Жыл бұрын

    Thanks for the tutorial! Is there a default timeout on WaitAsync() or will that wait indefinitely?

  • @emmanueladebiyi2109
    @emmanueladebiyi21094 жыл бұрын

    Nice explanation👍

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Cheers

  • @oganovdavid
    @oganovdavid3 жыл бұрын

    This is the best channel! Thanks you so much for teaching all the stuff in an easy way!

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Thank you for watching)

  • @salehdanbous6783
    @salehdanbous6783 Жыл бұрын

    Thank you Anton, as always you discuss subjects that not a lot of people explain. If you are updating a financial account would it be better to use a semaphore or to use Rowversion and optimistic concurrency?

  • @RawCoding

    @RawCoding

    Жыл бұрын

    If you have 2 machines, semaphore is inside your app, at that point you would need a "distributed lock". Row version and retries is better.

  • @uttamsuthar9940
    @uttamsuthar99403 жыл бұрын

    Awesome explanation...

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Cheers

  • @uttamsuthar9940

    @uttamsuthar9940

    3 жыл бұрын

    @@RawCoding even others videos are too informative

  • @fredrikfehre
    @fredrikfehre4 жыл бұрын

    Well played sir! :)

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Ta

  • @zealtypedcode3119
    @zealtypedcode31193 жыл бұрын

    Self taught here your instructions are outstanding , I will be Grateful if you do tutorials about massaging concepts like rabbit MQ or apache kafka

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    At some point!!

  • @clearlyunwell
    @clearlyunwell2 жыл бұрын

    Beautiful 🤩

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    Cheers

  • @huyvole9724
    @huyvole97242 жыл бұрын

    thank you so much

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    Thank you for watching

  • @oleksiy1752
    @oleksiy17522 жыл бұрын

    Thanks!

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    Thank you for watching)

  • @TheJessejunior
    @TheJessejunior3 жыл бұрын

    this was good!

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Thank you for watching

  • @NguyenNguyen-ly2yt
    @NguyenNguyen-ly2yt Жыл бұрын

    Your explaination very clear. thank you for your video. BTW, I really really miss LINQPad since I change to the Mac M1 :(

  • @RawCoding

    @RawCoding

    Жыл бұрын

    Mee too brother

  • @evrame.microwize
    @evrame.microwize Жыл бұрын

    Great video! Simple and elegant real-world scenario, thank you for the video! I have came across a rather interesting problem where a block of code can't be allowed access by more than one thread, and that seemed like a perfect example for implementing the usage of the SemaphoreSlim class, however, I have an additional problem, my app will work on three nodes under a load-balancer and all three connect to the same database (the block of code checks and updates some data), and that will cause problems, this way the SemaphoreSlim will not help me in that situation. What do you suggest?

  • @RawCoding

    @RawCoding

    Жыл бұрын

    You need a distributed lock or message passing

  • @yawar110
    @yawar1103 жыл бұрын

    nice one! - just a side note that SemaphoreSlim is a disposable object. so may be its a good idea to dispose it once used to save the resources.

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    If you need to dispose of it, dispose of it :)

  • @neilvermeulen5283
    @neilvermeulen52834 жыл бұрын

    Thank you.

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    No thank you

  • @samsal073
    @samsal0733 жыл бұрын

    Thanks for the video ....i like how you keep things simple. Im carious how this compare to other thread pool concepts for example the use of Parallel.Foreach where you specify Max # of threads? Also not sure about the yield use here, is it possible if we return each task at a time and the task finishes (hypothetically) before returning the next is possible the waitall will exit?

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Sorry I don’t understand neither of your questions, I can’t compare it to Parallel.Foreach they are completely different, and the last part just confuses me

  • @samsal073

    @samsal073

    3 жыл бұрын

    @@RawCoding sorry for the confusion. I guess my comparison to parallel.Foreach comes from the fact that like semaphoreslim you can limit how many threads can run asynchronously but maybe semaphore is how you can do it with async await concept. Regarding 2ed question i was trying to understand the use of keyword yield in "yield return callGoogle", doesnt that return each task one at a time to the Task.WaitAll in the Main function?

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Oh for the 2nd question watch my generator video

  • @sujitraul1097
    @sujitraul10974 жыл бұрын

    thanks for this tutorial. how have you coded the dump() method?

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    It’s a method only available in LinqPad

  • @sujitraul1097

    @sujitraul1097

    4 жыл бұрын

    @@RawCoding thanks !! I thought you have written an extension method.

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Nope, that’s just LinqPad

  • @ultramasculine
    @ultramasculine2 жыл бұрын

    I love you dude

  • @becomingweleteeyesus6735
    @becomingweleteeyesus67352 жыл бұрын

    Oh wow. I LOVE YOU.

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    Cheers

  • @DedicatedManagers
    @DedicatedManagers3 жыл бұрын

    At around 7:32 I don’t understand how your calls aren’t blocking... the CallGoogle function awaits the _client call to google, then prints the result. So doesn’t that complete the call to google before returning? I would think each call to CallGoogle would be blocking. Is it because it returns a “task” that each “yield return” in CreateCalls doesn’t get blocked by that await? (I’m not even sure I’m asking my question correctly. I’m a JavaScript programmer trying to learn C#. Is a task like a promise in JavaScript?)

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    That’s a good question. Yes Task is almost exactly like a promise. The reason they are not blocking is when I invoke CallGoogle it creates the Task and I don’t await on it, so the loop never stops and it quickly creates 200 tasks for me which all run asynchronously. All the 200 Tasks are awaited in a blocking manner by Task.WaitAll (there is a async version of this which is non blocking) in JavaScript you have the Promise.all function which is the non blocking version. Think of this like this we would take a list of strings and map them all to axios get requests, and the use Promise.all to await on them all so all requests are running asynchronously however in the “then” callback we just print the status code, internally between when the promise is resolved and the status code is printed the thread is awaiting, outside of the promise execution continues

  • @dariodusper7068
    @dariodusper70683 жыл бұрын

    Does semaphore slim work also between more assemblys, like mutex did?

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Never used Mutex

  • @mohammedabozobida8580
    @mohammedabozobida85804 жыл бұрын

    I have question in another topic which is AsNoTracking and Tracking in entity core what is the difference ?

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Not sure why you can’t google this question but here you go docs.microsoft.com/en-us/ef/core/querying/tracking

  • @cfndiaye
    @cfndiaye4 жыл бұрын

    Good 👍, what tools you use for this coding?

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    LinqPad

  • @cfndiaye

    @cfndiaye

    4 жыл бұрын

    @@RawCoding thank you

  • @User_Masuri
    @User_Masuri4 жыл бұрын

    I wish I could give you 1,000 likes!

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Thank you))

  • @ahmerkhan7479
    @ahmerkhan74793 жыл бұрын

    Great

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Thanks

  • @abdulmoiz3348
    @abdulmoiz33482 жыл бұрын

    Please, can you do one video on AutoResetEvent & ManualResetEvent ? Thank you.

  • @IMateme
    @IMateme4 жыл бұрын

    Genius

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    cheers :)

  • @clearlyunwell
    @clearlyunwell2 жыл бұрын

    👍🏽

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    👍

  • @ahmetsse
    @ahmetsse4 жыл бұрын

    Thanks for sharing . Nice to know this. Is it possible to make such implementation; lets say semaphoreslim sm.=new semaphoreslim(20) I want to put some sleep/timebreake after 20 request.

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    There’s no need to put sleep or break the semaphore is the break/sleep when you AwaitAync it will free the thread until the semaphore has more space.

  • @ahmetsse

    @ahmetsse

    4 жыл бұрын

    @@RawCoding I want 5 seconds breake, between first 20 peope and second 20 people

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    You will need to do batch releases then.

  • @eshika1336
    @eshika13364 жыл бұрын

    actually, I am working on my friends project it on c# and I want to popup a website from that software but we don't know how to change website links from server or database, ​we just need to change website link daily

  • @RawCoding

    @RawCoding

    4 жыл бұрын

    Semaphore can't help with this sorry

  • @asagiai4965

    @asagiai4965

    4 жыл бұрын

    Are you asking how to get the data from server or how to create links automatically

  • @Kitulous
    @Kitulous2 жыл бұрын

    500 запросов в гугл - верный способ, чтобы тебя реально "в гугле забанили" XD

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    Не там надо немного побольше постараться))

  • @claucometa
    @claucometa3 жыл бұрын

    Probably then if I wanna have a gate at all endpoints I do some sort of midleware? nO CLUE how to do so.

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    I’d advise against middleware because that could pause your server. You want to bring this to your business logic level rather.

  • @dvdrelin
    @dvdrelin Жыл бұрын

    'Try catch finally' would be more safely here with semafore releasing in finally section.

  • @uniquename2386
    @uniquename2386 Жыл бұрын

    What is Dump function and how to implement this?

  • @RawCoding

    @RawCoding

    Жыл бұрын

    It’s LinqPad specific

  • @MikhailGolnoshchekov
    @MikhailGolnoshchekov3 жыл бұрын

    You are using the initialCount parameter, but there is also a maxCount parameter. Please explain what happens if you add maxCount?

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    I never used it tbf, but I’d imagine it’s the upper bound that you can go up to if you release more than you await

  • @MikhailGolnoshchekov

    @MikhailGolnoshchekov

    3 жыл бұрын

    @@RawCoding That is, if, for example, initialCount = 5, maxCount = 10: This means that when 7 requests are executed simultaneously, 5 of them will be executed immediately, and two - a little later. But if there are 11 requests, then 5 will be executed immediately, 5 a little later, and 1 will not be executed?

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    If you lock and release for each request you’ll never end up past 5, so maximum 5 requests. I don’t actually know of any use cases for having a max count so can’t help with an example sorry.

  • @noraholmberg2303
    @noraholmberg23032 жыл бұрын

    so is semaphore and semaphore slim the same thing?

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    They do the same thing as in they are a semaphore, performance wise semaphores lim is better

  • @dholloway543
    @dholloway5432 жыл бұрын

    Wouldn't it be so much easier to just make that method not async so the call doesn't continue past and loop back for the result. Ending up with the the same outcome and less processing?

  • @dholloway543

    @dholloway543

    2 жыл бұрын

    I guess if you use more than 1 it would make since this way to utilize more than 1 thread Now that i think about it and like he says as the developer you would need to tune it

  • @RawCoding

    @RawCoding

    2 жыл бұрын

    Today most environments are multithreaded, blocking threads is a waste of resource. If we make the method non async that means we would have to block the thread, we want to avoid this.

  • @vivek.tiwary
    @vivek.tiwary3 жыл бұрын

    Is there anyway to know gate is occupied?

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    You can check the available count

  • @vetald1979
    @vetald19793 жыл бұрын

    Great. Statement that SemaphoreSlim is a newer version of Semaphore and it needs to be used in all the cases is incorrect, Semaphore is OS kernel mode object can be used for interprocess sync, SemaphoreSlim is a pretty much perpetual loop while(true) { if (!bResourceIsFree) continue; return; } => it's fast, but the cost is CPU usage

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    From what I see in the source code , waitAsync will create a task and store it in semaphore state as well as return it, release will queue that task to complete it on the thread pool. I don’t see any loop.

  • @vetald1979

    @vetald1979

    3 жыл бұрын

    @@RawCoding Right. The loop is implemented in sync version. My bad

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    No worries, didn’t know the Semaphore was working on the kernel level tho thanks for that ;)

  • @zlatkoherzl1314
    @zlatkoherzl13143 жыл бұрын

    I'm not gonna subscribe to this channel...No, I'm not...Damn it.

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Welcome:D

  • @zlatkoherzl1314

    @zlatkoherzl1314

    3 жыл бұрын

    Thx, nicely explained and demonstrated.

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Thank you for watching!

  • @yasser2768
    @yasser27683 жыл бұрын

    I don't see the point having your face in a programming video. That's not watchable.

  • @RawCoding

    @RawCoding

    3 жыл бұрын

    Wow dude

  • @MikhailGolnoshchekov

    @MikhailGolnoshchekov

    3 жыл бұрын

    Normal face)) I don't know English well, but thanks to facial expressions and gestures, everything is clear!