Which do I use, ConfigureAwait True or False?

Sdílet
Vložit
  • čas přidán 2. 08. 2020
  • In this video we answer the ever popular question "Which do I use, ConfigureAwait True or False?".
    The direct answer to this question is:
    - If you are a writing code for the UI, use ConfigureAwait(true).
    - If you are writing code in a library that will be shared, use ConfigureAwait(false)
    If you want to know why, then keep watching until the end, because I teach you the difference between ConfigureAwait(true) and ConfigureAwait(false).
    We start by understanding exactly how the await keyword in C# works. You learn about the continuation task and how to properly use ConfigureAwait to control which thread the continuation task runs on and why that's important.
    We talk about why the UI code relies on ConfigureAwait(true) and what happens if you set ConfigureAwait(false). Hint: you'll get a threading exception.
    We'll also cover why you need to use ConfigureAwait(false) in all of your library code to help protect the consumers of your code from encountering deadlocks and other threading issues.
    Be sure to watch my new Pluralsight course "Introduction to Prism for WPF":
    pluralsight.pxf.io/bE3rB
    Sponsor Me:
    github.com/sponsors/brianlagunas
    Follow Me:
    Twitter: / brianlagunas
    Twitch: / brianlagunas
    Blog: brianlagunas.com
    GitHub: github.com/brianlagunas
  • Věda a technologie

Komentáře • 147

  • @BrianLagunas
    @BrianLagunas  Před 3 lety +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 Před 2 lety +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  Před 2 lety

      Thanks for sharing your insights

    • @SherifAli-xx7xt
      @SherifAli-xx7xt Před 4 měsíci

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

    • @NicolaiPrang
      @NicolaiPrang Před 3 měsíci

      ​@@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. czcams.com/video/zhCRX3B7qwY/video.html

    • @JustNrik
      @JustNrik Před 16 dny

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

  • @martinbratt4593
    @martinbratt4593 Před 3 lety +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  Před 3 lety

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

  • @vaibhavachanty3659
    @vaibhavachanty3659 Před 9 měsíci +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 😍

  • @niranjannt637
    @niranjannt637 Před rokem

    These short videos are awesome Brain. Learning a lot.

  • @strandloper
    @strandloper Před 3 lety +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.

  • @jessegador
    @jessegador Před 3 lety +3

    Brief but accurate and precise explanation. Thanks.

  • @blakepell7139
    @blakepell7139 Před 2 lety +6

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

  • @vipinkrishna131
    @vipinkrishna131 Před 3 lety +2

    Explanation at its best!! Thanks a lot !

  • @BashaBill5
    @BashaBill5 Před 3 lety +2

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

  • @bhoopalsingh4463
    @bhoopalsingh4463 Před 3 lety +3

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

  • @88spaces
    @88spaces Před 5 měsíci +1

    Nice and clear explanation. Thank you.

  • @julianturner6203
    @julianturner6203 Před 3 lety +2

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +1

      Thank you very much for the kind words.

  • @Faygris
    @Faygris Před 6 měsíci +1

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

  • @FernandoMoreira
    @FernandoMoreira Před 3 lety +2

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

  • @mihaimyh
    @mihaimyh Před 2 lety +1

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

  • @amrelsher4746
    @amrelsher4746 Před rokem +1

    It is the first time I understand ConfigureAwait Thank you.

    • @BrianLagunas
      @BrianLagunas  Před rokem +1

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

  • @zerologics5105
    @zerologics5105 Před 3 lety +1

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

      That's great to hear. Thanks for watching.

  • @angelochiello
    @angelochiello Před 3 lety +2

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

  • @user-mr-m12312
    @user-mr-m12312 Před 3 lety +1

    Great video, thank you Brian!

  • @AvnishKumar7
    @AvnishKumar7 Před 3 lety

    Again an awesome video. Thanks brian.

  • @VinuP2023
    @VinuP2023 Před 3 lety

    Informative as usual sir :)

  • @briannielsbergh
    @briannielsbergh Před 2 lety +1

    Great video :)

  • @heshamabdo6024
    @heshamabdo6024 Před rokem +1

    Thank you so much ❤❤❤

  • @asitkumarmohanty2579
    @asitkumarmohanty2579 Před rokem +1

    This is awesome.

  • @AlexS-gn9tq
    @AlexS-gn9tq Před 3 lety +3

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +1

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

  • @_ganesh_khatri_
    @_ganesh_khatri_ Před 3 lety

    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  Před 3 lety

      If you look at my video on reporting progress from a task (czcams.com/video/zQMNFEz5IVU/video.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.

  • @VinuP2023
    @VinuP2023 Před 3 lety +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  Před 3 lety

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

  • @mallen1846
    @mallen1846 Před 3 lety +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  Před 3 lety +2

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

    • @mallen1846
      @mallen1846 Před 3 lety

      @@BrianLagunas perfect, thanks

    • @DaviBittencourt
      @DaviBittencourt Před 3 lety +1

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +1

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

  • @chrispybee
    @chrispybee Před 3 lety

    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  Před 3 lety

      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 Před 3 lety

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +1

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

  • @rafaspimenta
    @rafaspimenta Před 3 lety

    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!

  • @PauloMorgado
    @PauloMorgado Před 3 lety +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  Před 3 lety

      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 Před 3 lety

      @@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  Před 3 lety

      @@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 Před 3 lety +1

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

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

  • @nishant07kumar
    @nishant07kumar Před 3 lety +4

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

  • @Unison_007
    @Unison_007 Před 2 lety +1

    Спасибо!!!

  • @eugene00777
    @eugene00777 Před 3 lety

    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  Před 3 lety

      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 Před 3 lety

      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.

  • @PaulSebastianM
    @PaulSebastianM Před 2 lety

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

  • @sergiotardo
    @sergiotardo Před 3 lety +1

    thanks!!!!!

  • @abbaskhan.786
    @abbaskhan.786 Před měsícem

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

  • @satyad833
    @satyad833 Před 3 lety +1

    excellent

  • @manofqwerty
    @manofqwerty Před rokem

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

    • @BrianLagunas
      @BrianLagunas  Před rokem +1

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

  • @jamesbarrow
    @jamesbarrow Před 3 lety

    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  Před 3 lety +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.

  • @yaroslav7105
    @yaroslav7105 Před 2 měsíci

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

    • @yaroslav7105
      @yaroslav7105 Před 2 měsíci

      [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");
      }

  • @torreygarland14
    @torreygarland14 Před rokem

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

    • @BrianLagunas
      @BrianLagunas  Před rokem +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.

  • @harsheng
    @harsheng Před 3 lety

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

      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.

  • @Chris-xl3ly
    @Chris-xl3ly Před 2 lety +1

    Omg thank you

  • @ojasteredesai7827
    @ojasteredesai7827 Před 3 lety +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 !!

  • @lerocher2182
    @lerocher2182 Před 3 lety

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +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.

  • @mrjamiebowman1337
    @mrjamiebowman1337 Před 3 lety

    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  Před 3 lety +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 CZcams Samples repo and putting them all under there?

    • @mrjamiebowman1337
      @mrjamiebowman1337 Před 3 lety

      @@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.

  • @VladyslavPavliuk
    @VladyslavPavliuk Před 2 lety

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

    • @BrianLagunas
      @BrianLagunas  Před 2 lety

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

  • @KunalMukherjee3701
    @KunalMukherjee3701 Před 3 lety

    Make a playlist on the TPL

  • @InterRubke
    @InterRubke Před 3 lety +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  Před 3 lety

      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 Před 3 lety

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

  • @yevheniytymchishin8401
    @yevheniytymchishin8401 Před 3 lety +2

    How to close window from view model in WPF app?

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

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

  • @TinoCav
    @TinoCav Před 3 lety +1

    How do you handle a cancellable task?

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +1

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

  • @nipundesilva3518
    @nipundesilva3518 Před 3 lety +1

    nice

  • @mahmoudalaskalany
    @mahmoudalaskalany Před 3 lety

    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  Před 3 lety +1

      Simple, send your SMS asynchronously.

    • @mahmoudalaskalany
      @mahmoudalaskalany Před 3 lety

      @@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  Před 3 lety +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.

  • @dmitrykim3096
    @dmitrykim3096 Před 8 měsíci

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

    • @BrianLagunas
      @BrianLagunas  Před 7 měsíci

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

  • @cburys
    @cburys Před 11 měsíci

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

  • @IvarDaigon
    @IvarDaigon Před 2 lety +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 Před 2 lety

    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 Před 2 lety

      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  Před 2 lety +1

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

  • @a-s733
    @a-s733 Před 3 lety

    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  Před 3 lety

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

  • @ryanmcgowan3061
    @ryanmcgowan3061 Před 2 lety +1

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

  • @ThinkingNow
    @ThinkingNow Před 2 lety +1

    I wonder why they called it ConfigureAwait instead of something like PreserveContext. It's as if they were planning to have more configuration options and never got around to it.

  • @MiningForPies
    @MiningForPies Před rokem +1

    ConfigureAwait is a stupidly named method.

  • @rollinOnCode
    @rollinOnCode Před rokem

    interesting....