🌵 Can Async/Await block the main thread?

Sdílet
Vložit
  • čas přidán 26. 08. 2024

Komentáře • 12

  • @DotNetFun
    @DotNetFun Před měsícem +1

    great video . Thanks Saeed!
    The Background services in ASP NET Core always cause confusion between developers.
    In terms of Background Services, it will act in a blocking fashion until reaching the first async method ( that is why some say that it is best practice to do a "await Task.Yield()" at the first line of your background jobs

    • @sa-es-ir
      @sa-es-ir  Před měsícem

      Well said, happy you like the video

  • @TellaTrix
    @TellaTrix Před měsícem +1

    Very well spotted !

  • @Fikusiklol
    @Fikusiklol Před měsícem +1

    There's no guarantee that await returns the thread and runs on another.
    This code example is synchronous even tho it has multiple await keywords, thus code execution is continued using the same thread, until its blocked by that void method.
    If you want your program execution to be delayed - make it explicit, but inheriting from IHostedService interface instead of BackgroundService class.

    • @sa-es-ir
      @sa-es-ir  Před měsícem +1

      But using IHostedService won't solve the problem, we need to make sure to not use sync method in async methods. And it can happend a lot when using nuget packages that don't support async like Kafka consumer method!

    • @Fikusiklol
      @Fikusiklol Před měsícem +1

      @@sa-es-ir It actually does solve it kind of. You might be doing database migrations, so it's fine to block startup.
      And sync methods are fine, as long as they are not I/O bound. Your whole workflow is synchronous here. Whole point of await keyword is make your operations non blocking for threads.
      Anyway, still a valid point. Thanks

    • @sa-es-ir
      @sa-es-ir  Před měsícem

      @@Fikusiklol For migrations totally agree as they are critical for the application and db, thanks for sharing your insight

  • @DotNetFun
    @DotNetFun Před měsícem +1

    What do you mean by "main thread " ?ASP NET Core does not have main thread ( and synchronization context)

    • @sa-es-ir
      @sa-es-ir  Před měsícem +1

      You're right there is no synchronizationContext in the Asp.net core and the main thread is coming from my old habbits when was working with the winforms😁

  • @umpgod7573
    @umpgod7573 Před měsícem

    why await ServiceMethod(or other await's for layers) not acting like Task.Yield? i dont really get it. I would expect it act like Task.Yield so other layers would run on another thread. But as you said its really running on same thread until db.

    • @sa-es-ir
      @sa-es-ir  Před měsícem

      async methods starting 'synchronously' and it makes sense.
      Task is an object and one of those methods should create an actual Task to return and who did that in my example? Yes Task.Delay!