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.
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)
@@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
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.
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 😍
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
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.
@@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,
@@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.
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.
У меня не возникает DeadLock как в конце видео, хотя я сделал всё идентично. Я не понимаю почему он должен возникнуть. Почему .ConfigureAwait(true) вдруг должен ждать какого-то ответа от UI потока? Если мы говорим этим выражением, что хотим продолжать код в UI потоке. По логике второй поток должен выполнить дополнительный процесс, закрыться и передать управление обратно UI потоку. С чего бы второму потоку при await ждать первый?
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?
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
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.
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.
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 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
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...
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?
@@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.
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
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.
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.
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.
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.
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.
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)?
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.
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!)
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
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.
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)
Thanks for sharing your insights
This is the default in .net core right? but in .net framework it's the opposite. Did I understand it right ?
@@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
@@SherifAli-xx7xt What? From where you undertood that? ConfiureAwait(true) is the default in all frameworks and it has never been different.
This the most clear explanation of ConfigureAwait I've seen. Thank you for sharing!
Thank you very much
I agree too
Incredible! I was struggling with this in a project today and then this video pops up and answers the question! Thanks Brian!
I'm so glad this video was helpful to you. Thanks for watching
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.
I'm glad I could help
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 😍
Brief but accurate and precise explanation. Thanks.
Thanks for watching
These short videos are awesome Brain. Learning a lot.
Half of my code is ConfigureAwait(false)... Finally I know why.
I do API or library mainly.
You're doing it right 👍
It is the first time I understand ConfigureAwait Thank you.
I’m glad my video was helpful. Thanks for watching
How to close window from view model in WPF app?
Ohhh... There are a few ways to do this. I wonder which way I should show you :)
Thank you for the great explanation! I had a hard time understanding this before
Glad I could help
Subscribed! Thanks for the clear explanation!
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
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.
@@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,
@@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.
@@BrianLagunas in ASP.NET Lots of threads have a SynchronizationContext. And non of them are tied to a thread.
@@PauloMorgado that's good to know. I don't use ASP.NET, so thanks for sharing your knowledge. It's very helpful.
Nice and clear explanation. Thank you.
Thanks for watching
As always.. great vid. I'm trying to brush up on my Prism skills.. so I will see you again very soon. 👍
Sounds good to me! See you around :)
do these same rules apply for MVC/Blazor web applications?
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.
Super simple explanation. Thanks a lot. Now I understand it !!! :)
I'm glad it was helpful
У меня не возникает DeadLock как в конце видео, хотя я сделал всё идентично. Я не понимаю почему он должен возникнуть. Почему .ConfigureAwait(true) вдруг должен ждать какого-то ответа от UI потока? Если мы говорим этим выражением, что хотим продолжать код в UI потоке. По логике второй поток должен выполнить дополнительный процесс, закрыться и передать управление обратно UI потоку. С чего бы второму потоку при await ждать первый?
[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");
}
How do you handle a cancellable task?
Great question! And just in time. I was wondering what my next video would be 😀
Thanks Brian, I was struggling with the use of ConfigureAwait till now but not anymore. :)
That's great to hear. Thanks for watching.
Thanks, really simple video, I finally understood the ConfigureAwait concept.
Great! Thanks for watching
Explanation at its best!! Thanks a lot !
Thanks for watching
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?
No, the service should be ConfigureAwait(false). Only the consuming code of the service should set ConfigureAwait(true).
@@BrianLagunas perfect, thanks
The best summary of all to date. Great @Brian Lagunas ! Thanks for you do this vídeo !
@@DaviBittencourt Thank you so much for the kind words.
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
I'll have to think about this one and how to best present the information. Thanks for the idea.
Thanks Brian, I love these new videos. Your the best
Thank you very much for the kind words.
What about Asp.Net? In which cases should we use .ConfugureAwait(false) there?
AspNet isn't an issue because you don't have a UI thread
Basically all of the C# code I write is backend stuff, does this have any use case when not implementing a UI?
Not really. However, if you are using custom synchronization contexts then yes.
what's the default behavior if you don't use ConfigureAwait?
I think if you make a series on TPL and Async and Await it will be hit :)
Thanks for the tip
Question: Do you need CQRS when you have Application Services that can implement commands and queries as application service methods?
CQRS is not required
I have one doubt is await creating a thread? As you told it is executing in worker thread
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.
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!
For WPF?
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
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.
Great explanation! Thank you. Now I get it. You got a new subscriber ;)
Thanks for watching and the sub 😁
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.
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.
@@BrianLagunas However i shoot nyself in the foot using it in combination with IDurableOrchestrationContext, the orchestrator was not happy
Make a playlist on the TPL
Thanks for the suggestion
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
Simple, send your SMS asynchronously.
@@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
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.
Hah. I have had a question about ConfigureAwait at job interview few days ago. Thanks!
HA! That's funny. I guess this question is more common that I thought.
This is awesome.
Thanks for watching
Great video :)
Thank you
Great video, thank you Brian!
Thank you for watching
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...
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?
@@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.
Thank you so much ❤❤❤
Thanks for watching
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
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.
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.
Cooool...
Hi Brian,
How can i Configure or Add Interface Services for dependency injection in Wpf App? Please :)
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.
Again an awesome video. Thanks brian.
Thank you sir
Informative as usual sir :)
Thank you very much
So TL;DR, UI = true, Library = false. What happens when Library code is used in a UI?
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.
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.
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)?
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.
Brian Lagunas thanks for the reply. Would you say .NET CORE 2.x would be different.
@@chrispybee I don't see why it would.
ConfigureAwait should have been named RetainThread. Self explanatory this way.
Definitely needed a better name
Спасибо!!!
Пожалуйста
excellent
Thank you! Cheers!
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.
Agreed!
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!)
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?
@@ScottKFraley more specifically the UI thread of a Windows app.
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 !!
Thank you so much!
nice
Thanks for watching
Omg thank you
You're very welcome. Thanks for watching
When the if condition becomes false, then the task is skipped, but the task should not be skipped until the condition becomes true.
Glad that .Net Core got rid of synchronizaton context and we don't need to do that.
But platforms like WPF and WinForms do. So if you’re writing library code you still have to worry about it.
thanks!!!!!
Thank you for watching
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
async/await does not mean multiple threads automatically. It's also about synchronization context
ConfigureAwait is a stupidly named method.
Agreed
interesting....