C# Async/Await/Task Explained (Deep Dive)

Поділитися
Вставка
  • Опубліковано 23 гру 2024

КОМЕНТАРІ • 803

  • @rheinelroimanalo7321
    @rheinelroimanalo7321 2 роки тому +227

    Thank you programming Jesus!

    • @RawCoding
      @RawCoding  2 роки тому +68

      Stay blessed son

    • @sonikajha3788
      @sonikajha3788 10 місяців тому +2

      😂

    • @PerryCodes
      @PerryCodes 3 місяці тому +1

      Jesus is always pergmarily looking out for us!

  • @dattabansode6598
    @dattabansode6598 4 роки тому +302

    misunderstanding is extremely common. Many people are taught that multithreading and asynchrony are the same thing, but they are not.
    Example. You are cooking in a restaurant. An order comes in for eggs and toast.
    Synchronous: you cook the eggs, then you cook the toast.
    Asynchronous, single threaded: you start the eggs cooking and set a timer. You start the toast cooking, and set a timer. While they are both cooking, you clean the kitchen. When the timers go off you take the eggs off the heat and the toast out of the toaster and serve them.
    Asynchronous, multithreaded: you hire two more cooks, one to cook eggs and one to cook toast. Now you have the problem of coordinating the cooks so that they do not conflict with each other in the kitchen when sharing resources. And you have to pay them.
    Now does it make sense that multithreading is only one kind of asynchrony? Threading is about workers; asynchrony is about tasks. In multithreaded workflows you assign tasks to workers. In asynchronous single-threaded workflows you have a graph of tasks where some tasks depend on the results of others; as each task completes it invokes the code that schedules the next task that can run, given the results of the just-completed task. But you (hopefully) only need one worker to perform all the tasks, not one worker per task.

    • @RawCoding
      @RawCoding  4 роки тому +23

      Can you explain to me what made you think I'm misunderstanding something? To me it seems you explained what I explained but from a high level, which is what everyone does, and at no time did I make the following claim:
      > that multithreading and asynchrony are the same thing, but they are not.
      My explanation is based around - handing off a task to something else to work on, so in your example it would be a fryer (external process) frying an egg (working on a task), and we are not waiting for it (thread isn't blocked).
      When I go to explain that a different thread may complete the rest of our task it's like chef1 starting to cook an egg and chef 2 finishes it.
      If you are just giving another high level overview of asynchrony there are ton's of these, people are still looking for these videos because they want to understand the abstraction behind it.
      And I'll re-state I do think your explanation is correct and informative but doesn't cut where it needs to.

    • @exogendesign4582
      @exogendesign4582 4 роки тому +2

      Should've have find this comment sooner, I should learn both though.
      What I want was Synchronous for my project Since it depends on the completion of the first task before the next. that's why I there is no blocking in my app, since im using async, it really baffles me but this comment really made me see the difference, and the video made me understand how to right the code, good combination. Thanks for sharing your knowledge Datta Bansode. and Raw Coding you guys rock.

    • @emreaka3965
      @emreaka3965 2 роки тому +5

      @@RawCoding You said, "another thread is indeed going to complete the boiling process." but the man says "there is no another thread. it runs single thread." If I am wrong, please correct.

    • @ТарланИсмаилов-т2к
      @ТарланИсмаилов-т2к 2 роки тому +1

      ​@@emreaka3965 I think that the number of threads depends on operation type we need to execute (IO-bound or CPU-bound). IO-bound operations don't need additional threads, they use some external devices that don't need our help. But I might be wrong

    • @ZombieMagnum
      @ZombieMagnum 2 роки тому +2

      As I understand it from this video, the use of async/await DOES in fact sometimes automatically create additional threads, hoewever not necessarily for every async function or await statement. It is confusing that people insist that async/await is ''single-threaded asynchrony" when in practice it is not true. I do understand that multi-threading is a different concept, your explanation is great.

  • @mikecu2249
    @mikecu2249 2 роки тому +2

    This must be the Best Explanation about this Topic on our Planet!
    You didnt not only manage to create a crystal clear image, approch and explanation. You also picked the confused C# Devs up who still tried to figure out, what the clock is happening to my code?
    Thank you!

  • @ragtop63
    @ragtop63 11 місяців тому +5

    Although I already had a pretty good understanding of how all this works, I have to say that your explanation is by far the best that I’ve seen.
    Too many times other videos show you some simple implementation that really can’t be ported to the real complexities of asynchronous programming. So you leave those videos with a “Hmm, ok. I guess that makes sense. But how do I apply it to my specific situation?” kind of feeling.
    What you’ve done here is not given us the fish but instead taught us how to fish.
    A fundamental understanding of complex topics is always the best method.
    Great job!

  • @MiningMozo
    @MiningMozo 3 роки тому +166

    Step 1 - Complete High school
    Step 2 - Complete Colleges
    The next step is to figure out what the fuck is going on

  • @aronhegedus
    @aronhegedus 6 місяців тому +2

    this is really useful because you're showing us the inbetween code, rather than just telling us. I find that that's usually the most instructive, because I can then go and check that as well

  • @FroboDaggins
    @FroboDaggins Рік тому +3

    Hi, what is this .Dump() command?
    Is this something you wrote yourself or a NuGet package or the program itself?
    It doesn't seem to be a thing using C# on Visual Studio

    • @RawCoding
      @RawCoding  Рік тому +2

      it's a method provided by LinqPad, it's a fancy Console Writeline

  • @pratikzirpe315
    @pratikzirpe315 3 роки тому +53

    I haven’t seen anyone else explain such complex concept with such ease and still thorough - to the point. Thank you 🙏🏻

  • @decentwig5648
    @decentwig5648 10 днів тому

    Async has never really clicked until today, thank you very much.

  • @rafiul41
    @rafiul41 Рік тому

    One of the most underrated channels on UA-cam.

  • @cuzsleepisthecousinofdeath
    @cuzsleepisthecousinofdeath 2 роки тому +1

    Finally a person who's just like Jamie King(pardon me for making a comparison): straight to the point, showing the internal guts of things
    Subscribed instantly

  • @spuriustadius5034
    @spuriustadius5034 4 роки тому +62

    I got totally confused about Dump() and Dump(string s) until I realized that you are using some kind of built in extension method that your IDE (linqpad?) somehow defines for you. Once I understood that, it was super clear.

    • @RawCoding
      @RawCoding  4 роки тому +10

      Awesome! glad it didn't get in the way too much :)
      Yeah linqpad is like a mini development environment, as you can see I get to run my code instantly instead of waiting for the app to compile/start etc... and the data vizualisation that you get through Dump can be pretty incredible :)

    • @nobytes2
      @nobytes2 3 роки тому +14

      pretty weird tbh, just use console write like every other human 🙄

    • @RawCoding
      @RawCoding  3 роки тому +37

      No

    • @Jwhite1979
      @Jwhite1979 3 роки тому +11

      100% this! I'm 1:49 into the video, and I pull out C# In A Nutshell, find nothing, Google "String dump method", find nothing, search through UA-cam comments for someone, for the love of god, anyone explaining what the hell this .Dump method is all about! Thank you Spurius. Today, you're the hero.

    • @RichardONeil
      @RichardONeil 3 роки тому +2

      @@RawCoding agreed...Linqpad is the greatest tool on my belt to quickly work things out. You get all the cruft out of the way and can hone directly in on an algorithm that you are trying to build, or understand. I highly recommend buying it to everybody that does this for a living.

  • @hsnnoznn
    @hsnnoznn Рік тому +3

    Man, I usually take the information I need and close the video but you are absolute legend. I can not skip without a huge thanks. You explained it very well. Again, thanks a lot.

  • @DynamicalisBlue
    @DynamicalisBlue 20 днів тому +1

    Thanks this is great. I couldn’t sleep without knowing.
    I’ve always just used it but when I heard about JS Event Loop I was like “C# definitely doesn’t have an event loop right?” but I needed do confirmation.
    One thing I’m still a bit confused about is that since the tasks can be completed from any thread, how is it I’m able to safely use other objects without running into concurrency issues?
    For example, if I had two separate Async functions that waited on some network request but upon completion, they both write to a shared data container.
    I’ve somehow never encountered an issue with this but I’m confused how as if two threads try to write to the same data, it should lead to issues.

  • @aleksandermirowsky7988
    @aleksandermirowsky7988 Рік тому +19

    Rust's async/await functionality operates in a similar way, as it also expands into a state machine.
    It has been explained by Rust experts multiple times, but your explanation takes it to another level.
    The ability to visualize the intermediate generated code is just the icing on the cake.
    Great stuff, happy to see that you're still an actively posting on UA-cam. Instantly subscribed and activated notifications.

    • @RawCoding
      @RawCoding  Рік тому +1

      Thank you really appreciate it!

  • @emrealtuntas1319
    @emrealtuntas1319 2 роки тому +2

    After 05:51 i directly clicked like button.

  • @jimsteinPeerless
    @jimsteinPeerless 4 роки тому +62

    You do overemphasize the importance of threads like everyone trying to explain Async does.
    It is a nice very demo but (this is not covered by this video) if you in the first example replace the await Task.Delay(300) with a busy loop (the same as in the main function) there will not be another thread spawn and everything will execute on a single Thread. This is task concurrency on a single thread(?).
    Task.Delay is not CPU bound but the busy loop is CPU bound. So Task.Delay is good for simulating an IO bound Task and therefore you get continuation on another thread. The threads are operating on a layer below concurrency, so you do not need to have multiple threads to have Task concurrency(?).
    Kind regards

    • @RawCoding
      @RawCoding  4 роки тому +3

      Thank you for sharing

    • @mrcalico7091
      @mrcalico7091 4 роки тому

      @@RawCoding Thankfully, You're the teacher here!

    • @matthewkeron1448
      @matthewkeron1448 4 роки тому +1

      schooooled him

    • @ВадимН-о9х
      @ВадимН-о9х 4 роки тому +3

      Can someone please explain me what Jimstein Peerless meant?
      As he said, i replaced "await Task.Delay(300)" with CPU bounded task (the loop shown in the video for example):
      await Task.Run(() => {
      var a = 0;
      for (int i = 0; i < 100_000_000; i++) {
      a += i;
      }
      Console.WriteLine("CPU-bound task in running on ThreadId = " + Thread.CurrentThread.ManagedThreadId);
      });
      And i still see it being executed on another thread (Console.WriteLine shows thread id different from the main thread id).
      OR did he meant not using async/await and just start a raw CPU bound loop? But then it would be totally synchronous program and it is not the point of this video. But he still got so many likes on his comment. So seems like people found it useful. I am so confused...

    • @RawCoding
      @RawCoding  4 роки тому +3

      I guess I haven’t explained the Task.Run in this video where it’s literally a task you give the thread pool to execute, if you have a Synchronous Task method that returns a task without having async await , it will literally wait for the function to finish executing to give you the result of a Task object, like a normal function you are just waiting for the return value.

  • @TJahmusick
    @TJahmusick 4 роки тому +32

    This is exactly how I wanted this explained to me. Incredible! Thanks!

    • @RawCoding
      @RawCoding  4 роки тому +1

      Thank you for watching))

  • @geerivana
    @geerivana 3 роки тому +1

    Your videos are way better than any other official online courses

  • @tarlanismailov5228
    @tarlanismailov5228 2 роки тому +2

    It's clear when you talk about IO-bound operations because that operation can be completed out of the current CPU and there's no point to wait until it's done and additional threads aren't needed. But what about CPU-bound operations? If asynchronous programming implies 1 execution thread, then how CPU-bound operation can be executed without blocking this 1 thread that we have?

    • @RawCoding
      @RawCoding  2 роки тому +1

      Async implies the work will be completed somewhere else, concurrently or parallel you don’t know. Handing off a task to a network card in io bound, is the same as handing off a task to a cpu processor in cpu bound.

    • @tarlanismailov5228
      @tarlanismailov5228 2 роки тому +1

      @@RawCoding so based on the above, for example, Task.Delay() operation which is IO-bound will be executed out of our isolated execution environment (I made conclusion that it is isolated) and no additional threads will be added, right?

    • @RawCoding
      @RawCoding  2 роки тому +1

      You won’t know if a thread was added or no

    • @tarlanismailov5228
      @tarlanismailov5228 2 роки тому +1

      @@RawCoding I mean within our application

    • @RawCoding
      @RawCoding  2 роки тому +1

      @@tarlanismailov5228 it highly depends and varies from situation to situation. But you won't know.

  • @speakoutloud7293
    @speakoutloud7293 4 роки тому +14

    Man, I just can't get enough of your videos. You rock with this! Keep it up.

    • @RawCoding
      @RawCoding  4 роки тому

      Cheers, glad you liked them

  • @Esurnir
    @Esurnir 3 роки тому +1

    Thank you for clearing up this absolute swamp of complexity that is async await in c#

    • @RawCoding
      @RawCoding  3 роки тому

      Thank you for watching))

  • @hlazunov
    @hlazunov 2 роки тому

    This is the insane video about async/await in .NET. I have never seen a better explanation of async in .NET. Thanks a lot.

  • @zhh174
    @zhh174 4 роки тому +1

    thank you so much. no one explained it on youtube. they just show the use of async and await.

    • @RawCoding
      @RawCoding  4 роки тому

      Cheers, that’s what my problem with all the tutorials were :)

  • @rmcgraw7943
    @rmcgraw7943 6 місяців тому

    I have a good idea for a video…Consider this…you have a UI, a service layer, a business layer, a data services layer, and a data store layer. Should you, or would you, have async methods that awaited each subsequent layer, or would you have a UI layer that had async methods/controllers (so you could await calls to the service layer and/or business layer), and would those subsequent down tier calls also be LABELed as async methods, themselves having calls to deeper layers that it awaited…OR, would you have async UI Methods that awaited down tier(business layer) calls to methods (that were not LABELed async [the keyword]) that simply returned Task. That is to ask, would you chain down tiers like Async UI awaits Async Service that awaits aync Business that awaits async Data, etc, or would you have Async (to enabled await) UI that awaited Task returning Service that called Task returning Business, etc? TRUST ME, it MATTERS ALOT! The labeling of methods as async that have no await in them has a non-negligible cost in context switching and state persistence, not to mention the garbage collection involved in cleaning all those state machine allocations.

  • @gaming4fun419
    @gaming4fun419 4 роки тому +1

    So how does this work if you have more threads than cpu cores? Is it something like the stack in javascript? Do the Threadpool consists of 'open' threads so you don't have to create and shut down threads to use Task or is it a thread handler that opens and closes threads for us?
    Is this a correct understanding?
    Step 1 = (get kettle)
    State Machine {
    Step 2 = Async Task (start boiling water on the stove)
    Step 3 = Async Task (send kid to fetch tea) | (water still boiling)
    Step 4 = (get cups) | (still boiling) (kid still getting tea)
    Step 5 = [stop and wait for kid]
    Step 6 = (Put tea in cups)
    Step 7 = [stop and wait for water]
    }
    Step 8 = Pour water.
    If this is correct, what happens if there are only two cpu cores available? If threads are 'doers' that would mean I am a thread, the stove is a trhead and the kid is a thread but with only two cores only two of us can be active at the same time. If we were to consider the stove to be external, like a gpu, how does that relate to the thread pool?
    State machine still confuses me a bit as well. Is the entire process here a 'serve tea' state machine? If a Task starts another Task that it then at some point waits for, is that a nested state machine?
    A lot of questions, sorry if I seem a bit daft, but I would love to understand this better.

    • @RawCoding
      @RawCoding  4 роки тому +2

      Thanks for the comment, there's alot there.
      > So how does this work if you have more threads than cpu cores?
      imagine if you had a 1000000 meals to cook (threads), but you only had 1 stove (cpu) and 4 burners on it (core). Some meals are waiting for ingredients some are waiting for customers to order them, you might start cooking a meal on burner #1 you might finish it on burner #2 or any other one. There is also a thing called context switching you can read about it here (en.wikipedia.org/wiki/Context_switch)
      > Is it something like the stack in javascript?
      don't know
      > Do the Threadpool consists of 'open' threads so you don't have to create and shut down threads to use Task or is it a thread handler that opens and closes threads for us?
      the Threadpool consists of background threads, your application will start with an optimal amount of threads, if new ones are needed Threadpool will make those (not necasserily triggered by async/await). Threadpool background threads are seperate from the main foreground thread. Tasks (meals) are automatically put on to relevant threads (cores), by the ThreadPool (stove).
      > If this is correct, what happens if there are only two cpu cores available?
      It is correct, after each await execution may resume on ANY thread and ANY core. Essentially you have no computation to do at that point because child and kettle are external, they are not on your computer.
      > If threads are 'doers' that would mean I am a thread
      preciseley, if your wife was there helping you make the tea and asking the child to fetch the tea on your behalf you are running in parallel
      > the stove is a trhead and the kid is a thread but with only two cores only two of us can be active at the same time.
      The kid and kettle (if by stove you mean kettle) these are external, they are not part of the process, they do not run on our cpu.
      > If we were to consider the stove to be external, like a gpu, how does that relate to the thread pool?
      Threadpool lives in the process the process get's notified by an interupt from the gpu (en.wikipedia.org/wiki/Interrupt) threadpool and gpu are completley seperate, and communication via interrupt message passing.
      > Is the entire process here a 'serve tea' state machine?
      Each Task with an async keyword is a state machine
      > If a Task starts another Task that it then at some point waits for, is that a nested state machine?
      If that task is marked with async keyword, it is a nested state machine.
      Hope this helps.

    • @gaming4fun419
      @gaming4fun419 4 роки тому +1

      @@RawCoding Wonderful response! Big thanks for taking the time.

  • @razortier4284
    @razortier4284 Рік тому

    Great job. Not so many guys are explaining how it works under the hood with state machine

  • @LarrySmith1437
    @LarrySmith1437 3 роки тому +3

    Well done, sir. I struggled with how to present this topic to my dev department, your example helped a lot.

  • @TheFeaz
    @TheFeaz 4 роки тому +3

    Hey man, this (and your other video showing HOW to use async / await) was REALLY good information. Another person said it, but I'll say it again, this was the best presentation of this material that I've ever seen. I'm a senior software engineer with my company, and I've been here almost 20 years. Most of my work is in hard-core business logic, and I haven't done a lot with system-level stuff, multi-threading, and all that. With the changing system model these days and an emphasis on micro-services, I'm re-visiting these concepts (that and I'm doing some of my own private consulting now, doing web development, Docker containers, etc. and certainly am seeing a lot of this async stuff, particularly in the bakc-channel OAuth stuff.)
    Anyway, the biggest challenge I have learning this stuff in a meaningful way is that content out here usually goes one of two places-- It either shows very simplistic "hello world" type examples, that make would make a great "Await / Async 101" course or a college lab project, but in practice they don't scale well to anything resembling what we would actually DO in an enterprise application. On the other hand, there are task-oriented "how-to's" that show you the how but not the WHY. I really appreciated your deep-dive into this and a look at how the MSIIL implements this. That really gave a whole new dimension to my understanding of how this stuff actually works under the covers, and gives me some much-needed insight into how I could leverage these features in our enterprise applications.

    • @RawCoding
      @RawCoding  4 роки тому +1

      Thank you for your comment))

  • @ClassicRollPlayer
    @ClassicRollPlayer 2 роки тому +1

    i dont understand what the for loop at 9:44 is demonstrating ... can anyone explain? If make that too long the thread never changes... if I remove it altogether, the threads do change on #5. Thanks!

    • @RawCoding
      @RawCoding  2 роки тому +1

      It’s simulating a busy cpu, if you make it too long it might take a while to get through.

    • @ClassicRollPlayer
      @ClassicRollPlayer 2 роки тому

      @@RawCoding thank you!

  • @pieDesert
    @pieDesert 2 роки тому +22

    S-Tier explanation and demonstration. It is so difficult to find decent tutorials out there, but this one was no fat just cut right to the information I needed to hear and delivered with such simplicity. Also actually using the full time of the video to teach and explain and not self promote and advertise. Appreciate the raw commentary!

  • @StreetBladerBloke
    @StreetBladerBloke 3 роки тому +4

    Very clear and especially deep dive which is always a missing part in programming videos, you have nailed it.. thanks and keep it up with these videos they are pure gold..maybe u can create a course and sell it..I am sure deep dives are missing in today's programming world where instructors are just bothered about creame only but not the cake. You and Jamie king are the only ones who are taking it to another level. Thanks for ur efforts

    • @RawCoding
      @RawCoding  3 роки тому

      Cheers, there will be a course at one point

  • @_Ming_Ming_
    @_Ming_Ming_ 2 роки тому +1

    Thank you for this clear explaination sir! for this I will never skip ads in your video

  • @abhirammadhu2973
    @abhirammadhu2973 Рік тому +1

    You didn't add sugar😒
    BTW, this is the best video explaining async/await in C#. You're right. All other video just simply explains how to implement asynchronous program rather than explaining what exactly happens under the hood.

  • @gotham4u
    @gotham4u 2 роки тому +1

    Wow, I understood it finally .
    I was trying to understand async and await keywords for last an hour, but "yield" was not comprehensible. Thanks very much.

    • @RawCoding
      @RawCoding  2 роки тому

      Cheers, I have a video about IEnumerable and yield you can have a look

  • @martinrogachevsky5627
    @martinrogachevsky5627 2 роки тому +1

    One of the best explanations so far, great examples, thanks a lot!
    Only one thing didn't let me go through this on the first attempt is when you were explaining what network device is doing with the thread on your 'art', you said that it "frees" the thread. For someone who is not native speaker that sounded a lot like "freeze" the thread and really confused me for some time.
    So just be aware of these little verbal things but in general very helpful and worth sharing!

    • @RawCoding
      @RawCoding  2 роки тому +1

      Thank you, yeah I’m not a native speaker so might mess up some pronouncements

  • @TheJAGreaper
    @TheJAGreaper 4 роки тому +2

    I think the part you mentioned about the task executing on another thread is not technically correct especially considering the lack of the use of .ConfigureAwait(false).
    The whole concept of multi-threaded programming is entirely separate to the async programming model being that the async programming model is an abstraction for parallelism. It could be running on another thread, it might not, the default behaviour of the synchronisation context will resume the task on the same thread unless .ConfigureAwait(false) is specified. The exception to the rule, of course, being ASP.NET Core which uses a thread pool instead of the default behaviour of the synchronisation context.

    • @RawCoding
      @RawCoding  4 роки тому

      I don’t say the task is ran on another thread, the task may be completed by a different thread.

    • @TheJAGreaper
      @TheJAGreaper 4 роки тому +2

      @@RawCoding 7:00 - 7:05

    • @RawCoding
      @RawCoding  4 роки тому

      I see, yes you are correct, I’ve said it runs in parallel, which is not 100% correct, it runs synchronously up until await and then goes in to the big loop and a different thread completes the task. So there is a degree of parallelism but isn’t ran in parallel

    • @TheJAGreaper
      @TheJAGreaper 4 роки тому +3

      ​@@RawCoding Well no a different thread doesn't necessarily complete your task in parallel because you haven't told the synchronisation context to allow the task to run somewhere other than the captured context with .ConfigureAwait(false), Thus if the current synchronisation context only has access to one thread the exact same thread executes the code when it is freed up by the await call you to make with the Task.Delay method. This is especially dangerous when you are working with STAThread frameworks like WPF because the SyncronisationContext for the UI thread only has access to the UI thread making it incredibly easy to create deadlocks when working with WPF if you're not using .ConfigureAwait(false). (You can read more about it here from Microsoft themselves devblogs.microsoft.com/dotnet/configureawait-faq/ )
      Asynchronous programming with tasks can be parallel and they can be multi-threaded but they are no inherently so, what they are is an abstraction for thread management, not parallelism and multi-threading. You can have an entire application the uses async programming but only ever has one thread (not that you would want that). So when you explain it as if it is based around threading and parallelism you are passing on a very dangerous misunderstanding that will bite developers in the ass when they encounter these cases.

    • @RawCoding
      @RawCoding  4 роки тому

      I know it doesn’t necessarily complete the task, the example that I showed in the video I specifically show that the thread is working in the loop while the task completes. The exception is a WPF app where there is a UI thread that you need to sync with.
      Also thank you for sharing the valuable information.

  • @rookie1434-x6z
    @rookie1434-x6z Рік тому +1

    Only thing I am still confused of is, lets say FirstFunctionAsync awaits on SecondFunctionAsync, SecondFunctionAsync then awaits on the actual asynchronous I/O operation. Then does the thread gets released on when the first Function awaits the second one, and a new thread from thread pool is assigned to secondFunctionAsync, which again gets freed up when the actual async I/O is in progress. To sum up it's two threads that have been picked and released?

    • @RawCoding
      @RawCoding  Рік тому

      Amazing question!
      The thread will not be released until the final await in the call chain. So the code is synchronous up until then.

  • @spandanaotra2597
    @spandanaotra2597 3 роки тому +1

    I have a question regarding the differences between using a Task and a Thread.. I understand that Task can return a result and we cannot return a result when we use a thread. If I ignore that difference, when should i create a thread and when should i create a task? If task is also using the thread from threadpool... when i create a thread from where is that created? Please elaborate on that..

    • @RawCoding
      @RawCoding  3 роки тому +1

      A thread is where the task runs, you can think of tasks as units of computation and a thread is a place where code runs. Do not use threads unless you know what you’re doing. Always default to Tasks.

    • @spandanaotra2597
      @spandanaotra2597 3 роки тому +1

      @@RawCoding Can you please explain "Do not use threads unless you know what you’re doing" elaborately... If i had used a new thread to boil the kettle in the above example, what are the disadvantages or advantages compared to task?

    • @RawCoding
      @RawCoding  3 роки тому +1

      Spawning a new thread is slower, in addition to managing resources you have to manage threads. When I say know what you’re doing, I mean - there will be a situation where you taking control over managing threads will make the code run faster, because you’ll know exactly what cpu you’ll run on and what load your application will be under. But that is like 0.01% of the field will require this knowledge.

  • @lefrutit228
    @lefrutit228 2 роки тому +1

    tutorials such that are exaclty what youtube needs lol, I barely can find tutorials that I cant understand from the first watching, they're too simple, but this is excellent, thank you!!

  • @investmentjourney7912
    @investmentjourney7912 3 роки тому +1

    Best explanation till now, not just showing windows form for ui activeness like others. 👍

  • @No.School.dk_Colur
    @No.School.dk_Colur Місяць тому

    I thought I had an understanding of async/await but I didnt have nearly as much understanding as I have now tysm!

  • @PaulSebastianM
    @PaulSebastianM 3 роки тому +1

    Q: are .Net tasks eagerly evaluated upon creation, even before they are awaited? Because from your explanations, it seems that they start executing immediately after creation, and only awaiting a task blocks the current code path.

    • @RawCoding
      @RawCoding  3 роки тому

      What do you mean by eagerly evaluated? What exactly are we evaluating?

    • @PaulSebastianM
      @PaulSebastianM Рік тому

      Code. 😂 years later... what i meant was if they behave like JavaScript promises... and they don't. They build state machines that only run if awaited.

  • @Time_Leak
    @Time_Leak 4 роки тому +1

    Thanks for the clear explanation. It was really helpful to see IL that is responsible for all the magic.

  • @marketfinds
    @marketfinds 2 роки тому +1

    Excellent work, glad you went down into the IL Code. Helps make it clearer what magic is going on.

  • @ghazanfarabbas4187
    @ghazanfarabbas4187 4 роки тому +2

    Never seen such a insightful video before. Keep it up man...

  • @expertreviews1112
    @expertreviews1112 3 роки тому +1

    What's the underscore in the length of the loop? I searched but couldn't find...

    • @RawCoding
      @RawCoding  3 роки тому +1

      Just human readability feature.

  • @caglarcansarikaya1550
    @caglarcansarikaya1550 2 роки тому +1

    Hi, appreciate this video. Could define a thread like a worker, gives the job to the processor, and if its async, workers go to do some other things, then when processor finish the job, some other worker who is empty comes and grab this?

    • @RawCoding
      @RawCoding  2 роки тому +1

      You got half of it right, it’s just a worker or a job that you throw at a processor to work on or an external task in case of IO. You get the result of the task by awaiting it (anyone with a reference to the task can come grave the result)

    • @caglarcansarikaya1550
      @caglarcansarikaya1550 2 роки тому

      @@RawCoding Thanks for explanation, I will try some basics and I try to understand with ILspy :)

  • @shahzeb359
    @shahzeb359 3 роки тому +1

    I have question. If there are nested functions let's say upto 4 levels. Should all of them be async. Is it rule of thumb that it should be async or there is situation where we decide no this should be sync one..
    I personally watching this video because i am facing similar sort of situation. My DAL already written by somebody. I am exposing web service that in some situation call his dataaccess method which is sync in nature. Will my async method benefit me.? (as i m calling a sync method right at the bottom)

    • @RawCoding
      @RawCoding  3 роки тому

      If they are sync then no ) you can try Task.Run on that sync call but I don’t think it’s a good idea

    • @shahzeb5130
      @shahzeb5130 3 роки тому +1

      @@RawCoding you mean if all nested methods are async then there is no issue but if anyone of one them is sync then it is not good and go for sync top to bottom

    • @RawCoding
      @RawCoding  3 роки тому

      There is no pattern in here. You have to use async at one point and wherever you place it you’ll want to await it this will cause you to use Task all the way back to the root.
      Unless you are doing fire and forget

  • @ravanin
    @ravanin 4 роки тому +6

    What does Dump( ) mean? Can't seem to find it anywhere.

    • @RawCoding
      @RawCoding  4 роки тому +1

      LinqPad only :)

    • @gaming4fun419
      @gaming4fun419 4 роки тому +2

      @@RawCoding There are Nuget packages that give you Dump for C# as well.

    • @RawCoding
      @RawCoding  4 роки тому

      @@gaming4fun419 really? which ones?

    • @gaming4fun419
      @gaming4fun419 4 роки тому +2

      @@RawCoding I don't know if it differs much from the linq Dump functionality but servicestack.text.core has dump functionality and you can also give this a read:
      codingsonata.com/how-to-dump-object-for-debugging-purposes-in-csharp/
      I might have misunderstood something that makes linq dumps different.

    • @RawCoding
      @RawCoding  4 роки тому +1

      I’ll take a look cheers:)

  • @dominikchynoradsky4228
    @dominikchynoradsky4228 4 роки тому +2

    Hello Sir.
    What is the purpose of firstly saving the task into variable on line:
    "var boilingWater = BoilWaterAsync();"
    and then actually executing it a few lines later on line: (I assume it is being executed on this line and not on the one above)
    "var water = await boilingWater;"
    Would the result be the same if we just used the second line and wrote it as following?:
    "var water = await BoilWaterAsync();"
    I am sure the answer can be inferred from your video but I failed to do that
    Thank you for this informative video.

    • @RawCoding
      @RawCoding  4 роки тому +1

      When you put the task in to the variable you put the kettle on to boil the water. You don’t know when it’s going to finish but while it’s boiling you can do other things. When you call it with await you are going to check if it’s boiled if not then you are going to wait until it does

    • @dominikchynoradsky4228
      @dominikchynoradsky4228 4 роки тому +1

      @@RawCoding amazing way to explain it, thank you

    • @RawCoding
      @RawCoding  4 роки тому

      Glad you like it ))

  • @teurybazzo
    @teurybazzo Рік тому +2

    I don't know how to say thank you, i've a question, i'm learning about event loop and some concepts is very similar, this process that you explained is a kind of event loop ?

    • @RawCoding
      @RawCoding  Рік тому +1

      No event loops here - it’s a state machine.

  • @aresagathos2075
    @aresagathos2075 3 роки тому +1

    What i didn't understand was the rule "use async all the way from bottom to top".
    Why not make long running task, where you are dependent on result async, and have further up a "fire and forget" Task.Run ?
    In this case, the main?

    • @RawCoding
      @RawCoding  3 роки тому

      You could but generally you’ll sometimes want to know the result of the task and if there are many function calls in between they’ll most likely need to be async

    • @aresagathos2075
      @aresagathos2075 3 роки тому +1

      @@RawCoding Do they tough? Or is it just the easiest way to write it for people who don't understand async?
      Getting rid of some parallelism and let the bottom rest stay synchronous?

    • @RawCoding
      @RawCoding  3 роки тому

      I can’t give you a good example without writing up an essay , but it is nothing to do with people not understand async, it’s just generally propagated throughout your code.

  • @stevenstone307
    @stevenstone307 2 роки тому +1

    Awesome explanation mate. Funnily enough another thing I learnt in this video is that you can put underscores in big numbers lol

  • @kevinmarkandrada
    @kevinmarkandrada 3 роки тому +1

    On Check out 16:39
    Hi @raw coding, why is it that we put the await on the "var page = await task?" instead on "var task = await client.GetStringAsync("google.com")" ? Thanks !

    • @RawCoding
      @RawCoding  3 роки тому

      so I can show that the task is being finished on different thread.
      We kick off a task, do some work, and then wait for the task to be finished before proceeding.

  • @nullentrophy
    @nullentrophy 3 роки тому +1

    I got question: 13:28 "The thread that was running this process, returns to TP, and TP can use that thread for *something else* ." If UI is also running on Main Thread, does that mean that the moment we call the await(when thread returns to TP) UI becomes non responding? Or that "something else" is UI?

    • @RawCoding
      @RawCoding  3 роки тому

      When you await in main thread it keeps rendering the ui and it stays responsive. When the task completes the main thread executes the rest of the function

  • @neuro5261
    @neuro5261 3 роки тому +1

    So the way I'm understanding is that if there are two awaits then basically, the second await is blocked and the awaits are always executed in order am I right?

    • @RawCoding
      @RawCoding  3 роки тому +1

      Yes they are executed in order, the blocking is just the synchronous programming model illusion.

    • @neuro5261
      @neuro5261 3 роки тому +1

      @@RawCoding i see thanks for the explanation going to check out some of ur design pattern vids cheers🤘

    • @RawCoding
      @RawCoding  3 роки тому

      Hope you enjoy them )

  • @kopilkaiser8991
    @kopilkaiser8991 2 роки тому +1

    Thank you so much for taking the time to explain it. I have understood some of the concepts and I will need to rewatch it to better grasp the concepts. But still I was completely lost with this asynchronous programming, and was able to find some of the way by watching your tutorial. Thank you for simplifying the complex concepts. It takes a great mind to decode the entanglement which the async await Task brings in when you jump into it after being comfortable with synchronous programming. I will keep on digging into this until it is drilled deep into my mind.

  • @phongs2nhu
    @phongs2nhu 4 роки тому +1

    Good job, man.
    I'm from Viet Nam. So by watching your video, I studied new knowledge and English language. Of course, your voice is great with nice intensity.
    Thanks a million.

  • @jasonherrera7605
    @jasonherrera7605 4 роки тому +3

    Thank you, it is difficult for me to follow your English, but it has been the best explanation I have ever known.

    • @RawCoding
      @RawCoding  4 роки тому

      Awesome, thank you )

    • @magerehenk7579
      @magerehenk7579 3 роки тому +1

      why is it difficult to follow his english?

    • @RawCoding
      @RawCoding  3 роки тому

      I’m not a native speaker and some other people aren’t ether, so it’s a compounding effect

  • @iedi3
    @iedi3 10 місяців тому

    very impressive quality, and the relaxed atmosphere just perfect for some cigarettes and a beer (even though i stopped both), plus a reggae music in the background

  • @peternguyen9382
    @peternguyen9382 3 роки тому +1

    Hello, I still dont know "who" set the variable num =0 so when the ThreadPool call the movenext() it will execute the second part. thanks

    • @RawCoding
      @RawCoding  3 роки тому +1

      What do you mean? Do you have time stamp?

    • @peternguyen9382
      @peternguyen9382 3 роки тому +1

      @@RawCoding My question is : inside the MoveNext() function IL generated code
      if(num != 0)
      {
      code logic for part1 before async;
      }
      else
      {
      code logic for part 2 after async;
      }
      so my question is who set the value of num variable to 0 sothat when movenext() function is call it will jump to else block and then execute logic code for part2. Thanks

    • @RawCoding
      @RawCoding  3 роки тому +1

      It’ll be in code logic part 1

    • @peternguyen9382
      @peternguyen9382 3 роки тому +1

      @@RawCoding Could you tell me , how often the movenext() method will be called, it is call only when the network driver say to the threadpool that the work is completed ? or the movenext() method will be call in period of time?
      when the network driver tell the threadpool that the work is completed then the threadpool can find the exact state machine object in RAM and execute the movenext() method, am i right to say that?

    • @RawCoding
      @RawCoding  3 роки тому +1

      Yes you are correct, when external work is completed move next is called, as well as the 1st time the function is called

  • @nipungrover7058
    @nipungrover7058 Рік тому +4

    Legend has it that you understand programming better when jesus teaches you himself. Amen.

  • @jawaharjazz3842
    @jawaharjazz3842 3 роки тому +1

    but async and await won't create new thread to run. May I know how did you say it will be run on another thread?

    • @RawCoding
      @RawCoding  3 роки тому

      The ThreadPool will decide if a new thread needs to be created or not.

  • @user-rp9iis1en6h
    @user-rp9iis1en6h 3 роки тому +1

    How do u use this .Dump method, have u made an extension method?

    • @RawCoding
      @RawCoding  3 роки тому

      It’s part of LinqPad

    • @user-rp9iis1en6h
      @user-rp9iis1en6h 3 роки тому

      Thanks. Is it possible to create a global generic event listener? Something that will capture each and every events fired in anywhere into the system?

    • @RawCoding
      @RawCoding  3 роки тому +1

      Ehhhm kinda ye

    • @user-rp9iis1en6h
      @user-rp9iis1en6h 3 роки тому

      @@RawCoding Can you provide hints or any online link where I will find the instruction about how to do it?

    • @RawCoding
      @RawCoding  3 роки тому

      Nope

  • @kasra7885
    @kasra7885 4 роки тому +1

    You left no questions.
    And a good rhythm

    • @RawCoding
      @RawCoding  4 роки тому

      That’s what we like :D

  • @DuyNguyenHaDavis
    @DuyNguyenHaDavis 11 місяців тому

    as my understandings:
    1. heavier loop case: after the thread tells the network driver to get google page asynchronously, look like that same thread goes back and continues after the await keyword (thread id = 1 as in your demo).
    2. reduced loop size case: once that loop finishes and before it hits the await keyword, it is the end of the thread (1st part of code) so a new thread (thread id = 11) from the thread pool is issued to continue and pick the corresponding state machine in RAM (2nd part of code).
    So my question is why the same thread is used for heavier loop and reducing the loop size makes it runs on different thread? Shouldn't thread pool return a thread randomly after a part of code (await blocks) ends?

  • @noxagonal
    @noxagonal 2 роки тому

    Small summary for C++ people.
    Functionality vise "Task" is very similar to "std::future". "async" is similar to "std::async" except that the function itself is defined asynchronous instead of calling any function asynchronously. To get the same behaviour in C++ as in C# you could make a function that calls another function with "std::async" and returns "std::future"
    Implementation vise they're of course very different.

  • @MichaelVBrown-h2n
    @MichaelVBrown-h2n Рік тому

    Awesome video! Just what I was looking for. Also while I was diving into the Task code I had noticed a TaskStatus enum at the top. Immediately I was thinking that there must be some state machine at work happening here. So thanks for confirming that.

  • @DipakKumar-fc1lt
    @DipakKumar-fc1lt 4 роки тому +1

    Why you do not use Visual studio for coding purpose?

    • @RawCoding
      @RawCoding  4 роки тому

      I rather use LinqPad for teaching purpose

  • @ivailomanolov6908
    @ivailomanolov6908 3 роки тому +1

    Wait so what is the difference between parallel and async if async uses multiple threads internally when it needs too?

    • @RawCoding
      @RawCoding  3 роки тому +1

      parallel is parallel, async is sync or concurrent or parallel you don’t know, you can think of it as optimal

    • @ivailomanolov6908
      @ivailomanolov6908 3 роки тому +1

      @@RawCoding But is this not making some problems down the road? I mean you are not programming any explicit mutexes for example. How does the compiler know that it is safe to spawn / not safe to spawn another thread ?

    • @RawCoding
      @RawCoding  3 роки тому +1

      Nope, no problems will be created. As long as you are not sharing memory or mutating a shared object etc in the Tasks you’re good.c# has mutexes, locks, semaphores that you can use to provide synchronised access to a shared resource

    • @ivailomanolov6908
      @ivailomanolov6908 3 роки тому +1

      @@RawCoding Thanks Raw Coding ! You have an amazing channel ! Stay safe and greetings from BG :) Subs ++ ;

    • @RawCoding
      @RawCoding  3 роки тому

      @@ivailomanolov6908 Cheers ) you too

  • @AjitGoel
    @AjitGoel 3 роки тому +2

    This is a amazing video, first clear explanation of the async-await internals. Thank you Raw Coding.

    • @RawCoding
      @RawCoding  3 роки тому

      Thank you for watching

  • @MatthewMcGuff
    @MatthewMcGuff 4 роки тому +1

    Great video! So in the .NET runtime you have a thread pool which is what gets notified that its time for the state in the created state machine to change and move on the execution of code. I adding this comment as I first was hearing thread poll which made me think that this part of the run time was polling the awaited tasks to know when to continue execution of the state machine. Just to be really clear the Thread poll doesn't do any polling correct? It is just subscribed or listening for awaited tasks correct?

    • @RawCoding
      @RawCoding  4 роки тому +1

      No polling, the thread pool receives an irpc package or something like that which is an interrupt, and then resumes the execution of the task.

  • @НазарийСавиных
    @НазарийСавиных 2 роки тому +1

    Best explanation i've ever seen. Thanks!

  • @rohatsagar9967
    @rohatsagar9967 2 роки тому +1

    What happens if we have a function which returns a Task (without async and await)? Does it run Asynchronously?

    • @RawCoding
      @RawCoding  2 роки тому +1

      Depends what kind of task it is. If you do task.fromResult then no. Task.Run yes (cpu bound), io bound operations will await further down in the chain by default because its waiting for an interrupt call from the component

  • @javier01123
    @javier01123 4 роки тому +1

    so how can i create a function with a cpu bound process, and run it in another thread and await it?

    • @RawCoding
      @RawCoding  4 роки тому

      var someWork = Task.Run(myWork): where myWork is a function. This will run in the background and you can await on it later in the code.

  • @ibrahimalsurkhi9091
    @ibrahimalsurkhi9091 Рік тому

    Thank you so much for taking the time to explain it, Can you suggest any book to learn more about it and deep dive into it

  • @anpham871
    @anpham871 4 роки тому +1

    Thanks a lot!! You motivated me so much!! You are the best C# developer i've ever seen on youtube.

  • @Matt-zp8ng
    @Matt-zp8ng 3 роки тому +1

    I ran into a weird scenario that I'm curious to know why its behaving this way. In your demo, in the asynchronous version, you assign var boilingWater = BoilWaterAsync();, then a few lines down you call again var water = await boilingwater; and everything seems to run asynchronously in my demo, HOWEVER, if I just do var water = await BoilWaterAsync(), and try to use {water} in the interpolated string, the process seems to run Synchronously again....why is that?

    • @RawCoding
      @RawCoding  3 роки тому +1

      Because you are awaiting it, it’s synchronous mode, however the thread is not blocked there and can go do other things.

  • @hackywacky1799
    @hackywacky1799 3 роки тому +1

    Loved your video. Thanks a ton for putting great efforts. Can you please let me know how you are able to get the expanded async await code? When I try to use ILSpy I am only getting the original code written and not the state machine it expands to. Unable to find what I'm doing wrong.

    • @RawCoding
      @RawCoding  3 роки тому

      Eeeehm not sure tbh it just worked for me

    • @hackywacky1799
      @hackywacky1799 3 роки тому +1

      @@RawCoding Wasn't expecting such a quick response. Thanks. I finally found it. I had to go to View -> Options -> Decomplie and uncheck a few options like: "Decomplie async methods". Finally got to see the state machine code.
      Again, great explanation. Keep up the good work.

    • @RawCoding
      @RawCoding  3 роки тому

      Awesome! Thank you for sharing

  • @dunefedaykiin
    @dunefedaykiin 4 роки тому +4

    Awesome video, like always! Looking forward to the next video about the practical use of async/await!

  • @mrwillis5339
    @mrwillis5339 4 роки тому +1

    Useful to hear a concise explanation .

  • @jwange1
    @jwange1 4 роки тому +5

    Oh man! you really have a good head in clarifying things. thank you. Besides, what kind of editor do you use? interesting!

  • @sankaralingammuthusamy6142
    @sankaralingammuthusamy6142 Рік тому

    It was really superb explanation about async and await. Thanks bro keep up the good work

  • @andrzejjasinski8288
    @andrzejjasinski8288 2 роки тому +1

    Can anybody explain to me what is the Dump() method and how to use it correctly? I'm not familiar with it in c#.

    • @RawCoding
      @RawCoding  2 роки тому +1

      It’s part of LinqPad, it prints things to the window on the right.

    • @andrzejjasinski8288
      @andrzejjasinski8288 2 роки тому

      @@RawCoding I wonder why You use this editor instead of Rider or VS? Are there critical benefits coming from that?

  • @trustingod0
    @trustingod0 3 роки тому +1

    Im not a computer science person and i am completely confused. Is there a book i can read as a precuser to understanding what you are talking about. Thanks

    • @RawCoding
      @RawCoding  3 роки тому

      Which part are you confused about?

    • @trustingod0
      @trustingod0 3 роки тому +1

      @@RawCoding state machine and await being a checkpoint

    • @RawCoding
      @RawCoding  3 роки тому +1

      The state machine is like a self changing labyrinth, you enter it and exit when you enter it a second time it’s a different labyrinth. You can build your own state machines with custom logic, the point of the state machine is it will perform some logic and state will change, then behaviour changes based on the current state (you can see my state pattern video)
      The checkpoint (or await) is the point of change for the state machine (when the labyrinth would change). We enter the labyrinth at the point of await we exit the labyrinth the state of the state machine changes before we exit, next time we renter it we enter a different labyrinth performing different logic. if in the async state machine we never need to go off and wait for the external resource (like await Task.Delay(0)) that means even though we await we don’t really checkpoint, we don’t exit the labyrinth to re enter it again at a later point we just enter the 2nd version of the labyrinth straight away.

  • @onnuttig
    @onnuttig 3 роки тому +1

    Finally just a simple example of how this shit works, thanks man, instant sub

  • @tomaszwitkowski9545
    @tomaszwitkowski9545 3 роки тому +1

    I am in the fifth minute and I got understood it more than I had understood after the classes

    • @RawCoding
      @RawCoding  3 роки тому

      Hope you find the rest just as useful)

  • @calancehong7908
    @calancehong7908 4 роки тому +1

    Can I know what are those 1s that follow each dump output (1-5) at 9:51?

    • @RawCoding
      @RawCoding  4 роки тому +1

      It’s the thread id

    • @calancehong7908
      @calancehong7908 4 роки тому +1

      @@RawCoding I see. Thanks! Your tutorials are awesome. Keep up the good work buddy!

    • @RawCoding
      @RawCoding  4 роки тому

      Cheers

  • @forbin80
    @forbin80 4 роки тому +5

    Bruhhhh... I've been reading about and even using async for a couple years now and in 20 mins you just cleared up everything I didn't understand about the way this stuff works. All the weirdness I've seen in my code now makes perfect sense. Fantastic video, I can't thank you enough. By far the most clear explanation of async/await I've ever seen.

    • @RawCoding
      @RawCoding  4 роки тому

      Thank you, glad I could help:)

  • @TheFeaz
    @TheFeaz 4 роки тому +1

    I have a question for you... So one thing I've been struggling with while studying the use of this pattern is understanding what I need to in order to write my own natively awaitable functions. Most of the functions I see in the examples ultimately end up calling other awaitable stuff (like GetStringAsync on the HttClient), but what if I have some process-intensive code that I want to run asynchronously just because it's a fairly heavy subset of processing that I wan to do for a larger process, and I might have several of those to run in parallel? Imagine, just for instance, some code-based solution to the travelling salesman (an NP Hard problem), and I have a dozen requests to route customer orders for delivery routes. I assume, after watching this and your other video, that the ultimate aim for me is to use the Task. static object to manage the results of my traveling salesman problem and return those Task results out of my function (and perhaps only marking the highest-level functions as async to avoid the whole state machine issue you brin gup in your other video). Does that sound like I'm on the right track? From what I've come to understand, just marking a function async and then calling it with await doesn't make it run in parallel with anything else.

    • @RawCoding
      @RawCoding  4 роки тому +2

      So if part of a process you want to create a bunch of tasks/workload that will run in parallel or will consume the available compute efficiently use Task.Run() to kick the processes off, so if you have orderList, for each task you can create a Task.Run(generateDeliveryRoute), if you have 1000's or orders in your list and 8 cores on your compute, so let's say that'll be 16 processes, the ThreadPool will distribute the created tasks amongst the processes as best as it can generating 16 delivery routes at a time (this is known as CPU bound task)

  • @koenfrontatie
    @koenfrontatie 10 місяців тому

    really appreciate your style of teaching! you've helped me lots

  • @BryantCobarrubias
    @BryantCobarrubias 2 роки тому +1

    You're a very good teacher.

  • @mithunchopda
    @mithunchopda 4 роки тому +1

    What's the font you are using? It's very nice and readable

  • @Jiz39
    @Jiz39 4 роки тому +1

    Thank you . Can u explain web api. Net core using 3 layered and MVC but no view n presentation without entity framework .( In json format) dependency injection to perform basic CRUD operation. Tables With one to many, many to many relationship and with store procedure. Connect the sql server with web api

    • @Jiz39
      @Jiz39 4 роки тому

      Thank you..now I am watching ur previous videos n I feel helpful..

    • @RawCoding
      @RawCoding  4 роки тому

      Awesome

  • @asdasddas100
    @asdasddas100 4 роки тому +1

    Almost everywhere I go, people say that using async/await DOES NOT use a new thread (Unless you use ConfigureAwait(false)) but here you say that it does indeed continue on a new thread.
    I'm so confused as to why people would adamantly say async does not use new threads but you demonstrate that it does

    • @RawCoding
      @RawCoding  4 роки тому +1

      I guess they confuse it with how concurrency would work on a single thread, it’s not the case here.

    • @jimsteinPeerless
      @jimsteinPeerless 4 роки тому +3

      @@RawCoding Async/await does not necessitate new threads - whether or not async/await generates a new thread is dependent on the TaskScheduler used by the SynchronizationContext (in a single-threaded context like a WPF app).
      A Console app has no UI and therefore no 'UI thread'. dotNet Core is actually a Console app. Since there is no context, there’s no need for ConfigureAwait(false).
      Also, with Task.Delay with a No delay case, a delay of 0 seconds, the task scheduler is smart enough to distinguish this case and there is no new threads created. When you await Task.Delay, for more than 0 seconds, the current thread is freed to accomplish other tasks if the task scheduler decides it must be run asynchronously,

    • @RawCoding
      @RawCoding  4 роки тому

      Thank you for sharing

  • @davidhainovitz2838
    @davidhainovitz2838 2 роки тому +2

    Hi great explanation: Just would like a clarification: I'm referring to around 10:00 when you reduce the looping time. When its long the original thread still exists
    so the rest of the program uses it till the end even though the task uses a different thread as compared to when the loop is shorter so its released before the task
    completes and a different thread completes the program.
    Is this a correct understanding?
    Thanx

  • @xieweiling7543
    @xieweiling7543 3 роки тому +1

    The last part - the state machine is interesting!

  • @Skillamu
    @Skillamu Рік тому

    Very good explanation and demonstration. Great video!!

  • @Hypermommy
    @Hypermommy 3 роки тому +1

    Thank you for this very clear explanation of a sometimes confusing concept.

    • @RawCoding
      @RawCoding  3 роки тому

      Thank you for watching