Which do I use, ConfigureAwait True or False?

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

КОМЕНТАРІ • 147

  • @BrianLagunas
    @BrianLagunas  4 роки тому +35

    One point I forgot to make in the video was around performance. Using ConfigureAwait(false) is performs MUCH better because it's expensive to switch back to the original thread. This becomes especially important when doing async stuff in loops or performing expensive work after returning. Don't force the system to switch back unless you have to. Stick with ConfigureAwait(false) by default. Only set ConfigureAwait(true) if you really must run the continuation task on the original thread.

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

      It's not particularly expensive to switch contexts, the problem is that the original/UI thread might be busy doing something else (like actually drawing the UI) or it could be blocked by some long running synchronous operation and so your code has to wait for that block of code to finish before it can continue and then any UI update code has to wait for your function to finish before it can update (unless you pepper it with await Task.Yield()). So in that sense it can loosely be considered more expensive because you are taxing the UI thread when your code could have easily ran on another thread if it were written to be more async friendly (e.g. using Databinding instead of updating the UI directly)

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

      Thanks for sharing your insights

    • @SherifAli-xx7xt
      @SherifAli-xx7xt 10 місяців тому

      This is the default in .net core right? but in .net framework it's the opposite. Did I understand it right ?

    • @NicolaiPrang
      @NicolaiPrang 9 місяців тому

      ​@@SherifAli-xx7xt
      ConfigureAwait(true) is the default. You can't set a new default, though. So, you MUST just always set it to false everywhere you don't want it to return to the calling thread. Even though I personally use ConfigFalse a lot more than ConfigTrue. ua-cam.com/video/zhCRX3B7qwY/v-deo.html

    • @JustNrik
      @JustNrik 7 місяців тому

      @@SherifAli-xx7xt What? From where you undertood that? ConfiureAwait(true) is the default in all frameworks and it has never been different.

  • @blakepell7139
    @blakepell7139 3 роки тому +8

    This the most clear explanation of ConfigureAwait I've seen. Thank you for sharing!

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

    Incredible! I was struggling with this in a project today and then this video pops up and answers the question! Thanks Brian!

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

      I'm so glad this video was helpful to you. Thanks for watching

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

    Thanks for this. I've wondered about this before. Everyone just seems fo say always use ConfigureAwait(false). Now I know what it means and can intelligently decide when to use it.

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

    What an explanation man! I was seriously in a confusion for the difference between the two and almost got headache . But it's very clear now because of your video love you 😍

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

    Brief but accurate and precise explanation. Thanks.

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

    These short videos are awesome Brain. Learning a lot.

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

    Half of my code is ConfigureAwait(false)... Finally I know why.
    I do API or library mainly.

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

    It is the first time I understand ConfigureAwait Thank you.

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

      I’m glad my video was helpful. Thanks for watching

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

    How to close window from view model in WPF app?

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

      Ohhh... There are a few ways to do this. I wonder which way I should show you :)

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

    Thank you for the great explanation! I had a hard time understanding this before

  • @lucienlin3836
    @lucienlin3836 26 днів тому

    Subscribed! Thanks for the clear explanation!

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

    ConfigureAwait has is not directly about threads. It's about SynchronizationContext. WPF and its DispatcherSynchronizationContext or Windows Forms and its WindowsFormsSynchronizationContext happen to be tied to the UI thread, but that's not the case of, for example, the AspNetSynchronizationContext.
    referencesource.microsoft.com/#mscorlib/system/threading/synchronizationcontext.cs,8b34a86241c7b423,references

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

      That is correct, however what does a SyncContext do? It essentially allows a thread to communicate with another thread. So when breaking down a complex topic such as threading, I presented it as generalities which could easily be understood. The nuances of the SyncContext and how it works is generally irrelevant when wanting to understand where your continuation task code is running.

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

      @@BrianLagunas Nope!
      On ASP.NET it's just because of thread statics. It's not about communicating between threads, but guaranteeing that the data one expects to be attached to the thread is there. It's just a thread pool thread.
      On client UIs, it's just to guarantee that the code will be running on that thread. It's not an inter thread communication mechanism,

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

      @@PauloMorgado I look at it differently. I can ask Thread2 for its SynchronizationContext object, give it to Thread1, and then Thread1 can call SynchronizationContext.Send to execute the code on Thread2. In my thought process, that allows me to "communicate" or send data from one thread to another. I don't mean actual communication like some type of bus. Also noting, that not every thread has a SyncContext. As I alluded to, these nuances and technicalities aren't required to give an understanding of where a continuation task is being called and how ConfirgureAwait help controls that.

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

      @@BrianLagunas in ASP.NET Lots of threads have a SynchronizationContext. And non of them are tied to a thread.

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

      @@PauloMorgado that's good to know. I don't use ASP.NET, so thanks for sharing your knowledge. It's very helpful.

  • @88spaces
    @88spaces Рік тому +1

    Nice and clear explanation. Thank you.

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

    As always.. great vid. I'm trying to brush up on my Prism skills.. so I will see you again very soon. 👍

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

      Sounds good to me! See you around :)

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

    do these same rules apply for MVC/Blazor web applications?

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

      Well, not usually, but there are some cases where you will need to use it. If there is ever a custom SynchronizationContext or TaskScheduler present you'll need to consider it.

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

    Super simple explanation. Thanks a lot. Now I understand it !!! :)

  • @yaroslav7105
    @yaroslav7105 9 місяців тому

    У меня не возникает DeadLock как в конце видео, хотя я сделал всё идентично. Я не понимаю почему он должен возникнуть. Почему .ConfigureAwait(true) вдруг должен ждать какого-то ответа от UI потока? Если мы говорим этим выражением, что хотим продолжать код в UI потоке. По логике второй поток должен выполнить дополнительный процесс, закрыться и передать управление обратно UI потоку. С чего бы второму потоку при await ждать первый?

    • @yaroslav7105
      @yaroslav7105 9 місяців тому

      [HttpGet(Name = "GetWeatherForecast")]
      public async Task Get()
      {
      Task x = DoWork();
      x.Wait();
      return Enumerable.Range(1, 5).Select(index => new WeatherForecast
      {
      Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
      TemperatureC = Random.Shared.Next(-20, 55),
      Summary = Summaries[Random.Shared.Next(Summaries.Length)]
      })
      .ToArray();
      }
      private async Task DoWork()
      {
      Console.WriteLine("Work started");
      await Task.Delay(5000);
      Console.WriteLine("Work finished");
      }

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

    How do you handle a cancellable task?

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

      Great question! And just in time. I was wondering what my next video would be 😀

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

    Thanks Brian, I was struggling with the use of ConfigureAwait till now but not anymore. :)

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

      That's great to hear. Thanks for watching.

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

    Thanks, really simple video, I finally understood the ConfigureAwait concept.

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

    Explanation at its best!! Thanks a lot !

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

    If you have a service that handles all rest get requests that's injected into a viewmodel and called in the viewmodel do you simply add configure await true in the service? Keep in mind the view delegates a command to the viewmodel that ultimately calls the service method. I'm guessing that this is on the UI thread as it all originated from the UI?

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

      No, the service should be ConfigureAwait(false). Only the consuming code of the service should set ConfigureAwait(true).

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

      @@BrianLagunas perfect, thanks

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

      The best summary of all to date. Great @Brian Lagunas ! Thanks for you do this vídeo !

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

      @@DaviBittencourt Thank you so much for the kind words.

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

    Sir, here is a request video from me and I believe many of us need it.
    Can you please do a video on XAML/WPF debugging using any tools or any techniques you had developed over years such as finding failures in binding. I know one way to look in output window.
    Thank you

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

      I'll have to think about this one and how to best present the information. Thanks for the idea.

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

    Thanks Brian, I love these new videos. Your the best

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

      Thank you very much for the kind words.

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

    What about Asp.Net? In which cases should we use .ConfugureAwait(false) there?

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

      AspNet isn't an issue because you don't have a UI thread

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

    Basically all of the C# code I write is backend stuff, does this have any use case when not implementing a UI?

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

      Not really. However, if you are using custom synchronization contexts then yes.

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

    what's the default behavior if you don't use ConfigureAwait?

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

    I think if you make a series on TPL and Async and Await it will be hit :)

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

    Question: Do you need CQRS when you have Application Services that can implement commands and queries as application service methods?

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

    I have one doubt is await creating a thread? As you told it is executing in worker thread

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

      The async and await keywords don't cause additional threads to be created. Task.Run will schedule the work to be executed in the ThreadPool.

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

    Hi brian, how can I add a red border on textbox to validation a field? It will be nice has a tooltip to show the validation error. Thank you!

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

    Vidoe seems to have a small audio/video lag/sync issue, just at the beginning. Not sure if its just me. Thanks for the video

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

      Yes, this is an issue that I can ever see myself, but others have noticed. I have since switch microphones and that has seem to fix the problem. Let me know if you see this in my newer videos.

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

    Great explanation! Thank you. Now I get it. You got a new subscriber ;)

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

      Thanks for watching and the sub 😁

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

    I wonder why they have choosen to use ConfigureAwait(true) as a default, as most (or all of my asp.net core code) should benefit from ConfigureAwait(false). When working with UI code you are probably more aware of the UI thread switching.

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

      That's a great question. I don't have a lot of experience with ASP.NET, but it never made sense to me for ConfigureAwait to be true by default.

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

      @@BrianLagunas However i shoot nyself in the foot using it in combination with IDurableOrchestrationContext, the orchestrator was not happy

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

    Make a playlist on the TPL

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

    I have a question
    I have a number of users that may be from 10 to 2000 and i want to send to them sms and for each sms sent to user i need to insert it in database
    How to implement this without forcing the ui user to wait for all of these 2000 sms to be sent

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

      Simple, send your SMS asynchronously.

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

      @@BrianLagunas there is a problem in api from sms provider that is send only one message per time not a bulk message and if i send more than 30 message it crash i have to wait for 2 seconds between each 30 message so how to handle this situation

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

      I'm sorry, that's not something I can help you with. I do not have all the information and context about the problem or the environment required.

  • @AlexS-gn9tq
    @AlexS-gn9tq 4 роки тому +3

    Hah. I have had a question about ConfigureAwait at job interview few days ago. Thanks!

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

      HA! That's funny. I guess this question is more common that I thought.

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

    This is awesome.

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

    Great video :)

  • @user-mr-m12312
    @user-mr-m12312 4 роки тому +1

    Great video, thank you Brian!

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

    Besides UI/Apps.. how does this affect things like APIs? Also.. you should post a working repo of this... I wasn't able to replicate it myself. I had no issues...

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

      API's don't really have to worry about this at all. It is really only needed when you are returning to a UI context where the issue happens. I am trying to think of the best way to provide these samples, thinking about maintenance, discoverability, and how easy it is to get them. Maybe just starting a UA-cam Samples repo and putting them all under there?

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

      @@BrianLagunas I would appreciate that. I don't do al ot of UI development but I do see this in a lot of code that I use and I'm always confused by what it does... and how it works.

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

    Thank you so much ❤❤❤

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

    Hey Brian. I noticed that images in xaml create memory leaks.
    Case: Listbox with images, wait for images to be loaded, then clear collection, memory not releases.
    Also tried to load images from stream in view model, and then dispose stream, but images still exist in memory.
    Any ideas please? Also it would be very interesting if you make a video about memory leaks. Thank you

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

      I'm not familiar with that issue, but I don't really work with images. All my apps are LOB apps focused on data. One thing that comes to mind is to make sure you are binding to a collection that implements INPC. If you don't that will definitely cause a memory leak. You could try freezing the images, or using the DecodePixelWidth to tell WPF to not keep the image data in memory.

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

      1. I use ObservableCollection.
      2. I definitely freeze image. Because I am loading images from background thread.
      3. I can’t use DecodePixel because I need original images.
      Thanks for help.

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

    Cooool...
    Hi Brian,
    How can i Configure or Add Interface Services for dependency injection in Wpf App? Please :)

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

      Well, thats a complex topic overall, but essentially you'll need to choose a DI container, add it to your project, and configure it according to its documentation.

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

    Again an awesome video. Thanks brian.

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

    Informative as usual sir :)

  • @MrMatthewLayton
    @MrMatthewLayton 5 місяців тому

    So TL;DR, UI = true, Library = false. What happens when Library code is used in a UI?

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

    Thank you so much for these videos which are clearing all of our doubts about async and await. Your method of explanation is so much easy to understand, it just feels like child's play. I have one question please, I would like to know what is the right way to write async method which does not have any async method called inside it and has a value to return back. I may not sound clear but hope you understood my question. Thank you.

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

      If you look at my video on reporting progress from a task (ua-cam.com/video/zQMNFEz5IVU/v-deo.html), you'll see I have a method called LoopThroughNumber. You'll want to follow how I have that sample setup, but rather than calling a void method, you'll call your method that has a return value.

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

    Hey Brian - great explanation. I have a situation where we have a web page (MVC .NET CORE) and was reading about configureawait(true) vs false for that technology. Would I be right in thinking that for all await calls in the views, we should be using configureawait(true)?

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

      In general, if you are writing code in an ASP.NET MVC Controller you'll want to use the default of ConfigureAwait(true) becuase it is app-level code.

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

      Brian Lagunas thanks for the reply. Would you say .NET CORE 2.x would be different.

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

      @@chrispybee I don't see why it would.

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

    ConfigureAwait should have been named RetainThread. Self explanatory this way.

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

    Спасибо!!!

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

    excellent

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

    ConfigureAwait should default to false but it actually defaults to true.
    This was a poor design decision by Microsoft to sacrifice performance in order to appease beginner developers. The net result is; if you want your application to be very performant, you have to litter the code with ConfigureAwait(false) after every single effing function call.
    In practice the only time you ever need to use ConfigureAwait(true) is when you are touching UI elements directly because without it you will get cross-thread execution errors when you try to update UI controls via their properties. (Cross thread errors are yet another arbitrary and poor design decision by Microsoft).
    If your UI is using databinding (MVVM) OR there is no UI (Windows service, web API, console etc) then there is almost never a need to use ConfigureAwait(true) unless it is manipulating bitmaps or something else that is arbitrarily protected from cross thread manipulation.
    All ConfigureAwait(true) does is force the function to return back to the UI (or calling) thread but only when that thread is free to continue processing.. So it actually causes a bottlenecks in your application which can result in the UI becoming unresponsive if your async functions do a lot of heavy processing.
    And yes the function name ConfigureAwait() itself was yet another poor design decision by Microsoft because it does not even remotely describe what the function actually does.
    How about just calling it ReturnToContext() and just making people call it only when they actually want the function to return to the context it was called from.

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

    At the risk of being super pedantic, please define "coding on the UI." As in, are you talking about code within a Razor View [page], within a Controller, or...? (Thanks!)

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

      Okay, now that I've actually gone ahead and watched the video ( ;-) ), I'm guessing you mean in any WinForms or WPF button handler, et al, yes?

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

      @@ScottKFraley more specifically the UI thread of a Windows app.

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

    if you have super complex question. just ask to Brian Lagunas and BOOM.. you will get an answer super easy to understand !!!!!
    :)
    Thanks a lot !!

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

    nice

  • @Chris-xl3ly
    @Chris-xl3ly 3 роки тому +1

    Omg thank you

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

      You're very welcome. Thanks for watching

  • @abbaskhan.786
    @abbaskhan.786 8 місяців тому

    When the if condition becomes false, then the task is skipped, but the task should not be skipped until the condition becomes true.

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

    Glad that .Net Core got rid of synchronizaton context and we don't need to do that.

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

      But platforms like WPF and WinForms do. So if you’re writing library code you still have to worry about it.

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

    thanks!!!!!

  • @a-s733
    @a-s733 3 роки тому

    seems await is not running on other thread , the thread id looks similar. Or I miss something ...?? no idea... sorry did not get the point.. I think here is the answer.. www.skylinetechnologies.com/Blog/Skyline-Blog/December_2018/async-await-configureawait

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

      async/await does not mean multiple threads automatically. It's also about synchronization context

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

    ConfigureAwait is a stupidly named method.

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

    interesting....