8 await async mistakes that you SHOULD avoid in .NET

  Рет қаралды 313,374

Nick Chapsas

Nick Chapsas

Күн бұрын

Пікірлер: 245
@RawCoding
@RawCoding 4 жыл бұрын
Thank's for the mention :) also a very needed video on youtube, well done. One thing I could reccomend is to increase the font on Rider's menu's
@nickchapsas
@nickchapsas 4 жыл бұрын
You're absolutely right. I tried doing it before but at the time it increase the font on things that I didn't want increased and it just looked odd. Will try to fix that. Thanks for the suggestion!
@MrBarralex
@MrBarralex 4 жыл бұрын
Dude the cancelation token at endpoint lvl was awesome.
@daveblack8752
@daveblack8752 3 жыл бұрын
Agreed. I'd always wondered how to cancel the backend threads once the client canceled the request. Being able to pass the CancellationToken thru the endpoint answered that!
@protaties
@protaties 3 жыл бұрын
"You should avoid async void". Well that's where the word "avoid" from.
@kovalenkoihor4325
@kovalenkoihor4325 3 жыл бұрын
))))
@ciach0_
@ciach0_ Жыл бұрын
"You should make async void... Well void and not use it."
@logank.70
@logank.70 4 жыл бұрын
Something I did in a project when needing a resource loaded within a constructor was to build something that let me lazily load the data within an asynchronous context and await when I need it. It was just a small class built on top of Lazy that I called AsyncLazy. I can still pass in my interface that does the asynchronous call but stuff it inside of AsyncLazy and whenever I need that data I can just do (await _settingsLazy).; Plus, in my opinion, I like the way it reads. It tells whoever is reading that piece of code that the data is lazily loaded, cached after the first call, and is done within an asynchronous context.
@metlic5209
@metlic5209 3 жыл бұрын
About the last case, when you need to resolve service from DI, there is an article at msdn 'Dependency injection guidelines' with anti-pattern examples where is shown how you can deadlock your thread with an async factory.
@pchoudhary
@pchoudhary 2 жыл бұрын
I think simpler thing to do is to initialize the dependency and then inject it.
@fahtihi
@fahtihi 4 жыл бұрын
Really appreciate the timestamps in the description. Keep up the good work
@SixOThree
@SixOThree 3 жыл бұрын
Chapters in the timeline too!
@casperes0912
@casperes0912 3 жыл бұрын
I'm more curious about the async await mistakes I should be making
@sujithacharya007
@sujithacharya007 4 жыл бұрын
Great content Nick. You should have also shared some insight on 'ConfigureAwait' 😉
@nickchapsas
@nickchapsas 4 жыл бұрын
I actually intentionally left ConfigureAwait and .GetAwaiter().GetResult() because I will be covering them in a dedicated video, since it's just a big topic.
@aboimpinto
@aboimpinto 4 жыл бұрын
@@nickchapsas Will wait for that videos too!!
@oganovdavid
@oganovdavid 3 жыл бұрын
@@nickchapsas seems like you haven't uploaded that video yet. Please do so, will be glad to check
@victorcomposes
@victorcomposes 4 жыл бұрын
Ah man, I should update my personal project... Thanks alot Nick.
@lnagy88
@lnagy88 3 жыл бұрын
async Task is dangerous if it's an event handler, basically the Task object will not be assigned and not GC-ed, thus catching exceptions will not work. async void is the way to go when used in event handlers or expect to not GC.
@sdddv
@sdddv 2 жыл бұрын
I’m wondering why it's should be preferred since await should be called where result(or exception) is needed. I don’t use async/await for arrow(wrapper) function which is only prepares input parameters. And also use ContinueWith when need to re-cast result without awaiting public Task GiveMeInt() => Task.FromResult(1L).ContinueWith(task => (int)task.Result, TaskContinuationOptions.ExecuteSynchronously); Await is very optimized in core, but it’s much heavier in full framework.
@zitronenmelisse3
@zitronenmelisse3 2 жыл бұрын
Actually in the async void is bad example it is not the Task.Run that causes the process not to die but changing the return type to Task and what that does to the method behind the scenes.
@martinprohn2433
@martinprohn2433 2 жыл бұрын
Hi Nick, can you explain to me, why should I write "return await new ValueTask(numberToAdd*2);", if I could also write "return numberToAdd*2;" directly. To explain more, we are in an asyc method, so return a value directly is automatically wrapped in a Task (or in this case a ValueTask). So what is the benefit of this additional await?
@canabale
@canabale 24 күн бұрын
There is one usecase where you can kind of not await everything... and that is technical debt. I was facing quite a few cases, where a call just had too many references to be refactored at once. For such cases I used the shown methods for getting the Task results. But I totally agree, in theory even that could be awaited. Its just a matter of priortity.
@acidhauss7018
@acidhauss7018 2 жыл бұрын
The static async method is really clever, had that problem for years
@lollo4711
@lollo4711 3 жыл бұрын
COOL: Enumerable.Empty .. I didn't know
@styleisaweapon
@styleisaweapon 3 жыл бұрын
In VB6 we were told not to use DoEvents because it was bad practice. Now we are told to do it in an even more complicated way in C#/VB.NET, using await and async, a way that doesnt solve any of the reasons we were told not to use DoEvents back then and also has a more limited utility (its all or nothing with async, doevents is any time you want) In VB6 we were also told not to use OnError because it was bad practice. Now we are told to use exceptions, something less capable than OnError (see the distinction between Resume and Resume Next.) Spaghetti in the form of objects is still spaghetti.
@thygrrr
@thygrrr 7 ай бұрын
For the Ante part, this should be that if you get one of your cards STOLEN by a Bat, you have to take it out of your deck.
@ivandamyanov
@ivandamyanov 2 жыл бұрын
20:46 How do you register a method in DI? I'm probably not searching about the topic properly cause I can't find information about that and I've never done it. Thank you for the video btw, I am really interested in improving my understanding of all the scenarios around async/await and love videos you make about that.
@dhammond249
@dhammond249 3 жыл бұрын
As painful as it can be, I've definitely found situations where using the async keyword is not realistically possible. In a legacy application this can mean a huge change across a platform. Or for example a legacy 3rd party plugin that has some kind of hooks that don't support async for example But yeah... If you're writing a new code base just async all the things and thank yourself later
@nickchapsas
@nickchapsas 3 жыл бұрын
Legacy applications and await async are the worst possible combination really. You really really wanna refactor some stuff but your hands are tied.
@catafest-work
@catafest-work 3 жыл бұрын
... is supported starting with C# 7.0, good tutorial. A good video tutorial will be about your words: " in the dot net scenario there is no way that you cannot await a call ".Thank's for sharing ...
@GazziFX
@GazziFX 2 жыл бұрын
7:35 why you awaiting this ValueTask you can just `return new ValueTask(numberToAdd * 2);`
@DummyFace123
@DummyFace123 Жыл бұрын
That async task delay in a gamechanger for task cancelation, used to have to loop 😩
@JohnWilliams-gy5yc
@JohnWilliams-gy5yc 3 жыл бұрын
Brilliant gotchas picked. Very concise and understandable demo sequencing. You are a very good teacher, sir.
@AljRest
@AljRest 6 ай бұрын
Thank you so much for this video it has been enlightening!!
@leandrowitzke6405
@leandrowitzke6405 4 жыл бұрын
Awesome Nick. Clear and easy to understand. Keep simple. Thanks
@ruslanbocharov
@ruslanbocharov 4 жыл бұрын
catch (TaskCanceledException) when (cancellationToken.IsCancellationRequested)
@anyonefromsouth6447
@anyonefromsouth6447 2 жыл бұрын
10:54 ContinueWith is used in scenarios such as this: var task1 = service.GetValueAsync(id1).ContinueWith(...); var task2 = service.GetValueAsync(id2).ContinueWith(...); Task.WhenAll(task1, task2);
@mcintoshdev
@mcintoshdev 2 жыл бұрын
I have never used it that way. I use Task.WhenAll() when I have a variable length of bound tasks to perform.
@rishvaksreshta9464
@rishvaksreshta9464 2 жыл бұрын
Nick didn't really give a reason why once async should always be async. Can someone explain?
@nickbarton3191
@nickbarton3191 2 ай бұрын
How do you cancel a Task where it calls a blocking call from another API which you can't change, that's not designed to be cancellable?
@MohamedOmar-zw2bq
@MohamedOmar-zw2bq 4 жыл бұрын
Very nice indeed, especially the cancellation token demo 👍. Keep posting more videos about this topic 👏👏
@FatihTurkerFatih
@FatihTurkerFatih Жыл бұрын
Very well done
@lightandtheheat
@lightandtheheat 3 жыл бұрын
Just a note with the last one. Changing it into a factory makes DI way more complicated. An alternate solution that works fine is to offload your async construction calls into an async Initialize method. In the constructor, call your Initialize method and assign its resulting task to an instance variable. Then in your async methods that depend on the initialization to be completed, "await _initializationTask;" at the top. No need for factory, still works great with DI, and you can call async stuff safely from the constructor.
@nickchapsas
@nickchapsas 3 жыл бұрын
I think I don’t fully get it. How do you asynchronously await from the ctor?
@lightandtheheat
@lightandtheheat 3 жыл бұрын
@@nickchapsas You don't. You await the task that you've stored in the instance variable from the start of any methods in that class that are dependent on it, by which time it would have likely completed anyway.
@nickchapsas
@nickchapsas 3 жыл бұрын
@@lightandtheheat Oh no I would never do that. I like deterministic behaviors in the software I write.
@lightandtheheat
@lightandtheheat 3 жыл бұрын
@@nickchapsas I think KZbin is deleting my comments because of a pastebin link, so just in case, here's a pastebin id for an example: "Dask3TsG". It's still deterministic, just asynchronous-- the outcome is the same each time (deterministic), so long as you have a call to await the initialization task. An example use would be if you need to add a client certificate to an HttpClientHandler at construction, but need to fetch the certificate asynchronously.
@nickchapsas
@nickchapsas 3 жыл бұрын
@@lightandtheheat I really don't like this. If this thing is needed in multiple methods then you're literring every method with a state machine and an awaitable context that could be completed. You're wasting both memory and time and you're leaking a class level concern on a method that shouldn't know about it.
@L-E-son
@L-E-son 2 жыл бұрын
RE: "Don't sync over async in constructors" - do you have a clean solution for setting up this initialization pattern when using the Microsoft.Extensions.DependencyInjection namespace (IServiceCollection, AddScoped, AddTransient, etc.) for DI?
@donjon61
@donjon61 3 жыл бұрын
I liked the explanation for the cancellation token and AsyncInConstructors a lot. I didn't exactly know the reason for the tokens to be there, but it makes a lot of sense that a controller just continues to do what it was asked for. I'll probably take the static creation method, too. Quite a nice design.
@sen.alexandru
@sen.alexandru 3 жыл бұрын
I've watched a ton of your videos and after each one I keep saying to myself "how come this guy doesn't have at least 100k subs already?!"
@jonathandaniel7321
@jonathandaniel7321 3 жыл бұрын
not many people use dotnet
@ihorbond
@ihorbond 3 жыл бұрын
@@jonathandaniel7321 fake news. a lot of corporations do especially in fin tech space.
@ihorbond
@ihorbond 3 жыл бұрын
cause he is a Java guy disguised as C# (based on IDE)
@dracla26
@dracla26 3 жыл бұрын
Task.FromResult Nice touch!
@marcelocarvalho7049
@marcelocarvalho7049 4 жыл бұрын
Amazing! Applying into project right now! 🙏😁
@deathrade0111
@deathrade0111 4 жыл бұрын
Awesome tutorial Nick. One example of something you cannot make async (I haven't been able to). Is event calls on WinForms and WPF. Take the following Load event on a Form or WPF Window. public async void Load() I can do however if I try public async Task Load() it won't compile. Interested to know your work around to make these async. Custom events I can do, as I declare the delegate, but built in ones are tricky.
@JohnPeter-yf5jf
@JohnPeter-yf5jf 4 жыл бұрын
Wondering what to do for Property changes in WPF
@GregWilliamBryant
@GregWilliamBryant 3 жыл бұрын
Nick Chapsas, in your first example, could you confirm whether awaiting would actually result in the application closing. As the task would pass back control to the main thread and just exit?
@nickchapsas
@nickchapsas 3 жыл бұрын
It will completely fall over and stop running
@qwerty5689
@qwerty5689 4 жыл бұрын
Thank you so much for this. Best practices vids are the best.
@AzureFullstackDev
@AzureFullstackDev 4 жыл бұрын
good stuff from 00:01 ;)
@theMagos
@theMagos 4 жыл бұрын
The cancellation token should be used with care. Canceling a save operaton half-way through could leave your database in a undesirable state (half-saved objects).
@nickchapsas
@nickchapsas 4 жыл бұрын
Ideally all your db operations in a since call should be atomic. Breaking them down to multiple calls or having them be non-transactional is dangerous no matter whether you use a cancellation token or not
@Bourn77
@Bourn77 2 жыл бұрын
hi Nick, suppose i have a workflow with async method calls all the way to the repository, is it a good option to use "Task.FromResult" when i have one method which has no awaitable calls to force it async? or is it a better option to make the method simply syncronous?
@Jandalf430
@Jandalf430 2 жыл бұрын
"In netcore there is no context where you cant wait a task". What about the Startup class?
@Fafix666
@Fafix666 2 жыл бұрын
The problem I see with the last example, is that static methods are a pain to mock in unit tests. Injecting ConnectionFactory and then using it in specific methods to get MyConnection is probably a better approach? Unless the Connection has to be shared between methods, but it'd mean we need atomicity. Does it make sense to have multiple methods in such case?
@PaulSebastianM
@PaulSebastianM 4 жыл бұрын
9:10 Well, no. If you're implementing a foreign Interface and that doesn't support async methods, and you need to await async methods inside sync methods of that Interface, there's no other way but to force synchronisation.
@nickchapsas
@nickchapsas 4 жыл бұрын
I have never used a .NET library in the past 5 years that either isn’t purely async or doesn’t over both a sync and async alternative for its implementation. I am happy to take a look at an example and offer an alternative though
@Daniel-yl5fi
@Daniel-yl5fi Жыл бұрын
Hi Nick, How do you pass cancellationToken to Task.WhenAll()?
@kaisersolo76
@kaisersolo76 4 жыл бұрын
Always pass the CancellationToken - while I do agree with this in general , they should be employed tactically.
@nickchapsas
@nickchapsas 4 жыл бұрын
Yeah I forgot to mention that if you don't want that process to be cancellable then you shouldn't be passing the token. Something like an asynchronous email sending for example.
@kaisersolo76
@kaisersolo76 4 жыл бұрын
@@nickchapsas great stuff regardless, keep it coming!
@VinuP2023
@VinuP2023 4 жыл бұрын
Thanks Nick..
@Vlad-ib6iv
@Vlad-ib6iv 4 жыл бұрын
Realy like ur videos about .net. Are you going make video about delegates in c#? More about their usage, cause theory is quiet simple, but there very few good examples of their usage.
@huyvole9724
@huyvole9724 2 жыл бұрын
Really Readlly useful !!! Thank you
@e-cogs
@e-cogs 3 жыл бұрын
Thank you, this is very helpful
@fullmoonyeah1180
@fullmoonyeah1180 2 жыл бұрын
if an async operation doesnt return any result, just use fire forget. is it correct?
@Any1SL
@Any1SL 2 жыл бұрын
Steven Cleary has a few amazing blogs on this.
@NergalDaimonoz
@NergalDaimonoz 3 жыл бұрын
The part at 5:53 is very confusing to me. Why is wrapping the code from SomeBackgroundThingAsync in a try-catch which re-throws, magically making Task.Run aware that an exception has been thrown ? When you say at 5:26 "there is a way to change this, so it throws an UnobservedTaskException", have you done this on the side without showing it between your run at 5:12 and 5:53 ? I tried in a sandbox to simply switch between try-catch and not try-catch, but the result is the same : Task.Run wil fire-and-forget.
@Draekdie
@Draekdie 2 жыл бұрын
Task.Run is not aware that an exception has been thrown. The exception is simply logged in the catch of SomeBackgroundThingAsync.
@bongbui
@bongbui 3 жыл бұрын
hi Nick, when use EF Core with action Insert, Update, Delete data, we should pass CancellationToken? Thank you
@Zapo9668
@Zapo9668 2 жыл бұрын
Very cool video
@jradplowman
@jradplowman 2 жыл бұрын
I see so many of these in our legacy code base... Looks like it's time to refactor 😝
@vamsi8669
@vamsi8669 4 жыл бұрын
this is what we are waiting for. Thanks!
@TeamCykelhold
@TeamCykelhold 4 жыл бұрын
You could say we have been...awaiting it....dudu tsss...ok I'll see myself out.
@ryanhaney
@ryanhaney 2 жыл бұрын
Also, async void isn't bad, it just works differently.
@iamintosomething
@iamintosomething 3 жыл бұрын
Very useful video
@parsamehdipour2473
@parsamehdipour2473 8 ай бұрын
Nice🔥
@anilkumar8753
@anilkumar8753 Жыл бұрын
I think one can learn entire Go in lesser time than the C# async/await itself :)
@SECourses
@SECourses Жыл бұрын
In first case it is terminated because still you are running in the main thread. Async Await is not by default running in sub threads / tasks. Here my async await video : kzbin.info/www/bejne/f2XGn4uVpMl2Z68 . continuewith is good if you are not awaiting the task result.
@internetmarketingog2268
@internetmarketingog2268 3 жыл бұрын
How would I use await inside a catch statement in vb.net?
@stevehoff
@stevehoff 2 жыл бұрын
Hmmm I was taught, by MS that you should not always await every method that returns a task because that's a ton of overhead. If you are not doing something with the task return value there is no need to await. This creates state machines which adds not only CPU cycles but also the memory your app uses. Please explain why you think every task method should be awaited. Thanks!
@stevehoff
@stevehoff 2 жыл бұрын
I should add that yes, you should eventually await the the stack and can even mix awaiting and not awaiting in a single call stack.
@lawrencetsang3368
@lawrencetsang3368 2 жыл бұрын
I may add, that RUN TASK, thing, It is to wrap an otherwise NOT await-able method, for UWP and Windows Sdk App. (WPF programmer, don't know UWP, will be confused.) Example, Windows Sdk App, in side a converter -> will crash, if you copy a WPF converter and try to use on "IT": you need to do this: try { Task.Run(async () => { var stream = await file.OpenReadAsync(); dispatcher.TryEnqueue(async () => await BI.SetSourceAsync(stream)); }); return BI; } ___________ in other words: If you have a BIG method coded with WPF, do not want to recode it for UWP/WAP, That, run-task thing, is very useful. Another Example, with WPF, fetch SQL return from local database, it will wait and blocked, unit it is COMPLETED. Copy that block of code to UWP, it may not work, or crash. Because? the method will return immediately, before the result is completed. FIX? -> that run-task await thing.
@unnilunnium101unknown8
@unnilunnium101unknown8 Жыл бұрын
Which IDE is he using?
@charrystheodorakopoulos4843
@charrystheodorakopoulos4843 3 жыл бұрын
Κάνε ένα και για την ConfigureAwait για το λαό σου.
@arthurmelo88
@arthurmelo88 4 жыл бұрын
How can I inject async connection on my controllers contructors? I cant use this static approach on my controllers that extends ControllerBase
@nickchapsas
@nickchapsas 4 жыл бұрын
You can do that by creating a service, initialising in that new service and then injecting it in the controller
@sunilanthony17
@sunilanthony17 3 жыл бұрын
Nick, can you please explain this to me. @ the 11:19 mark, you are awaiting the number from an async call. Won't the next line of code run and fail if the await call takes a while?
@TheZubass
@TheZubass 2 жыл бұрын
Hey, what is the var:type extension?
@patrikbak8161
@patrikbak8161 4 жыл бұрын
Is it really true that SomeBackgroundThingAsync() is actually a background thing? I'd say it's synchronous until it hits an await and then it depends on the current sync context or task scheduler where the continuation carries on.
@nickchapsas
@nickchapsas 4 жыл бұрын
It’s actually a background thing yeah, you can get the source and try it yourself
@patrikbak8161
@patrikbak8161 4 жыл бұрын
@@nickchapsas It wouldn't be in a console application.
@Xorgye
@Xorgye 3 жыл бұрын
@@patrikbak8161 in the case of task.run it is registered in and running on the task pool. But with the void the code gets executed immediately up to an await, but after that... I know it will return to the controller and continue the controllers' path. But that function... It probably gets cleaned up by the GC. It would be the same as if you created a task 'dostuff' in a non async function. And in 'dostuff' yielded immediately. Unless you do something with the returned task, 'dostuff' will never continue it's code path beyond the yield.
@th9267
@th9267 2 жыл бұрын
Thanks for video. I have a question about a scenario I need to code. I have a process that will send a request file via SFTP and then I will need to wait for a response file to be created on the ftp server before I download and continue my processing. The response file could appear within 1min to 60mins. If I await this process, is there a way that I can say, give up after 60 mins?
@TheRealRslive
@TheRealRslive 3 жыл бұрын
Does value task still uses the threadpool ?
@LuxDefensor
@LuxDefensor 3 жыл бұрын
Hi, Nick! Thanks for the video. Can I ask you a probably dumb question? You see, I have this problem with async/await in WPF if I try to implement MVVM pattern. Turns out, in a view model properties can't be async. I looked it up on stackoverflow, but their solution is a bit too complex for me so for now I simply either go synchronous or don't do MVVM. But I'm pretty sure there must be some simple and correct way of doing this, which I don't know because I'm self-taught and lazy. After watching your video I thought, this is the person who can help me or at least point in the right direction. Thanks in advance.
@jessicafrankston7155
@jessicafrankston7155 3 жыл бұрын
I do this by having a base ViewModel class that implements the INotifyPropertyChanged, and that gets an Action injected that it can call to actually notify. In unit tests, injected Action just runs (whatever....), in real code, the injected Action conditionally invokes (CheckAccess/BeginInvoke) on the Dispatcher (of the window that did the dependency injection at startup). No async/await, though. Needs to use Tasks. Any better ideas to actually go async, appreciated.
@mariocamspam72
@mariocamspam72 2 жыл бұрын
@@jessicafrankston7155 You don't have to implement INPC manually in 2022; It's more error-prone and results in massive boilerplate blocks. Use the CommunityToolkit and inherit from ObservableObject. It also contains source generators accompanying the [ObservableProperty] attribute.
@christclamard1097
@christclamard1097 4 жыл бұрын
hey Nick, thanks for all those helpful videos. I have a question, what the name of the extension that displays the inline argument or parameters hint your code?
@nickchapsas
@nickchapsas 4 жыл бұрын
Heya. It’s not an extension, it’s a built in feature in the idea I am using, called Rider
@pkipChannel
@pkipChannel 4 жыл бұрын
Look for ReSharper. Visual studio big extention pack from the Rider authors.
@hannasamia6739
@hannasamia6739 4 жыл бұрын
Great Video, Short question do you know if they fixed the problem where cancelation tokens don't trigger in IIS? Cause it still a problem for me at least with the Controllers token in the API Thanks
@MrAndrei4777
@MrAndrei4777 4 жыл бұрын
Google bless you!
@dominicc1804
@dominicc1804 3 жыл бұрын
One await async mistake that YOU should avoid is 'return await Task...'. you should just return the task. 🙂
@nickchapsas
@nickchapsas 3 жыл бұрын
This is actually incorrect and I just published a video about this very topic. (explanation from Microsoft and David Fowler)
@anathimatshaya9909
@anathimatshaya9909 Ай бұрын
Looks like I can't use Async with ref params🤔
@anathimatshaya9909
@anathimatshaya9909 Ай бұрын
Had to use tupel
@erikzamecnik4914
@erikzamecnik4914 2 жыл бұрын
Once you go async always async is a mistake?
@troncek
@troncek 2 жыл бұрын
What's the IDE he's using?
@nickchapsas
@nickchapsas 2 жыл бұрын
JetBrains Rider
@davidmiko1102
@davidmiko1102 3 жыл бұрын
Hi Nick, I'd like to ask if you are using var just because you do not want to write the type of the variable or are there any other reason for that?
@nickchapsas
@nickchapsas 3 жыл бұрын
Hey, I'm using var because I think that my variable declaration name and value assignment should be more than enough to indicate what the type is. The type itself isn't important to me. I can clearly see what it is from the code without explicitly stating it.
@davidmiko1102
@davidmiko1102 3 жыл бұрын
@@nickchapsas Oh, okay, thanks! Something new to me.
@wordonice4457
@wordonice4457 4 жыл бұрын
The confusion around async / await in C# and consequently the importance of async / await in C# proves just how broken C# is, and how much it's in need of an overhaul, especially in this area. Too often, junior developers make these async / await mistakes. Even seasoned developers sometimes make these mistakes in their examples online. The worst part of it all is how the definition of async / await makes no sense. People coming off other languages that have some implementation of "async" always struggle to adjust to C#'s idea of async because it doesn't mean what they think it does.
@PaulSebastianM
@PaulSebastianM 4 жыл бұрын
Really? I don't think there's any confusion around it stemming from bad design, rather from bad understanding or old habits coming from other programming languages.
@wordonice4457
@wordonice4457 4 жыл бұрын
@@PaulSebastianM from my experience with junior developers, it's more to do with difficulty in grasping Microsoft's concept of await-async and not "bad" understanding per se. In fact, a simple search will tell you that await-async is THE MOST misunderstood concept in C#, and it so happens to be simultaneously THE MOST important concept in C#. When you have something this influential causing this much confusion, then there's something wrong somewhere. Even Microsoft does a poor job at explaining await-async properly
@protox4
@protox4 3 жыл бұрын
Well, C# pioneered async/await, which is leagues better than callback-hell. All other languages that adopted async/await took the idea from C#. It's a decade old now and not much has changed since its inception in C#, except ValueTask and custom task-like types and awaitables were added. [Edit] And async iterators recently added. I'm actually actively working on a project in my spare time with custom task-like types to simplify a lot of the confusing things about Tasks.
@matthiasschuster9505
@matthiasschuster9505 4 жыл бұрын
Did you check if they also count for F#, or is this just for C#?
@nickchapsas
@nickchapsas 4 жыл бұрын
Since these are CLR specific, they should stand true for F# as well
@Chiramisudo
@Chiramisudo 2 жыл бұрын
1:08 says "without further ado" and immediately contradicts himself. 😅
@lordicemaniac
@lordicemaniac Жыл бұрын
at 14:25 you returned Enumerable.Empty() in async method, shouldn't your rather return await Task.FromResult(Enumerable.Empty...) ?
@i_fuk_religion
@i_fuk_religion 10 ай бұрын
The cancellation token part is sic....
@CS-eh8eo
@CS-eh8eo 3 жыл бұрын
Nice content, do you know anyone similar who does kotlin ?
@MiceDevelopment
@MiceDevelopment 3 жыл бұрын
for fire and forget/return avoid configureAwait(false) will do isn't it ?
@nickchapsas
@nickchapsas 3 жыл бұрын
This really depends on the sync context of your app. In .NET Core you don't need it.
@MiceDevelopment
@MiceDevelopment 3 жыл бұрын
@@nickchapsas ouhhh okayy thank you nick ! :)
@mattc4153
@mattc4153 2 жыл бұрын
Can’t await in a constructor
@ArgeKumadan
@ArgeKumadan 4 жыл бұрын
How about using using(idisposible) on async tasks. And on your last solution: after i've done what u say, now i cant use ioc container to create instence of SomeService. What am i supposed to do now? I wanna inject SomeService to my controller via dependency resolver.
@FilipCordas
@FilipCordas 4 жыл бұрын
They added await using in c# 8. As for async in the constructor David Fowler recommends doing your async initialization in IHostedService before the app starts, for lazy initialization you can write a filter or middleware that will run your init logic before the request then just inject things a usual.
@ArgeKumadan
@ArgeKumadan 4 жыл бұрын
@@FilipCordas what u r saying sounds really good, but first we need to understand the concept. First we must understand what happens if we don't do it, what does it couse bla bla bla.
@stephenyork7318
@stephenyork7318 4 жыл бұрын
So what do you do with event handlers in desktop applications that have to be async void?
@nickchapsas
@nickchapsas 4 жыл бұрын
I don't think that exceptions in async void desktop app handlers can cause the app to crash so that usecase would be valid. That being said, I don't have enough experience with desktop apps so I am not aware of any alternatives
@gnack420
@gnack420 4 жыл бұрын
Event handlers are mentioned by Microsoft explicitely as being an exception to the "avoid async void" rule, so feel free to use 'async void' for those.
@LeMustache
@LeMustache 3 жыл бұрын
Just as the second Nick said - this is one of the reasons (if not the only one) you can even use void as return type for async functions. Because of event handlers.
@ivandrofly
@ivandrofly 4 жыл бұрын
good content
@Gaspa79
@Gaspa79 3 жыл бұрын
I think you can't await void anymore right?
@UntakenNick
@UntakenNick 3 жыл бұрын
What's with the "new Exception(message: "bla.." I had never seen that type of declaration before.
@michielarkema
@michielarkema 3 жыл бұрын
You can throw your own exceptions.
@UntakenNick
@UntakenNick 3 жыл бұрын
@@michielarkema I know, but I would have written it new Exception ("Message..") or new Exception () { Message: "Message.." };
@michielarkema
@michielarkema 3 жыл бұрын
@@UntakenNick The first one.
@UntakenNick
@UntakenNick 3 жыл бұрын
@@michielarkema But in the video he writes new Exception(message: "Message..") in lower case and inside the parentheses, which is what my comment was about.
@michielarkema
@michielarkema 3 жыл бұрын
@@UntakenNick oh that's just syntax highlighting from the ide.
@watchchat
@watchchat 3 жыл бұрын
Nice
@0w784g
@0w784g 3 жыл бұрын
Here's mistake #9 (or #1 imho). Avoid introducing async/await into a legacy codebase that does not use it, unless you're working with a team of async/await experts. Even then I'd say it's not advisable.
@mahmutjomaa6345
@mahmutjomaa6345 3 жыл бұрын
Also prefer ValueTask over Task
@nickchapsas
@nickchapsas 3 жыл бұрын
Only if the method isn’t doing async work most of the time, example: one every 5 minutes the method will cache a value asynchronously but the rest of the times it retrieves it from a local cache. Using it everywhere without context is bad
@daveblack8752
@daveblack8752 3 жыл бұрын
One caveat to using ValueTask (if you didn't know) is that it can only be awaited once. In most cases, you only need to await a Task once, but sometimes when bunching a number of async calls together with Task.WhenAll , you may find you need to await more than once. Especially true if you use the idiomatic approach of using 'await' to get the result of an already completed task (e.g. when using Task.WhenAll). I prefer to use 'await' over calling .Result on an already completed task since it is more clear IMO. See this thread for more info - github.com/davidfowl/AspNetCoreDiagnosticScenarios/issues/65
@rik0904
@rik0904 3 жыл бұрын
wait I can do every thing async EVERYTHING
What is Span in C# and why you should be using it
15:15
Nick Chapsas
Рет қаралды 254 М.
Офицер, я всё объясню
01:00
История одного вокалиста
Рет қаралды 2,3 МЛН
Как мы играем в игры 😂
00:20
МЯТНАЯ ФАНТА
Рет қаралды 3,1 МЛН
哈莉奎因怎么变骷髅了#小丑 #shorts
00:19
好人小丑
Рет қаралды 52 МЛН
Please Help This Poor Boy 🙏
00:40
Alan Chikin Chow
Рет қаралды 11 МЛН
That's NOT How Async And Await Works in .NET!
12:25
Codewrinkles
Рет қаралды 23 М.
Await Async Tasks Are Getting Awesome in .NET 9!
9:24
Nick Chapsas
Рет қаралды 95 М.
.NET and C# are in trouble. Here is what I'd do.
10:57
Ed Andersen
Рет қаралды 70 М.
What are record types in C# and how they ACTUALLY work
15:36
Nick Chapsas
Рет қаралды 121 М.
Writing C# without allocating ANY memory
19:36
Nick Chapsas
Рет қаралды 148 М.
How to use Async/Await/Task in C#
29:45
Raw Coding
Рет қаралды 75 М.
Офицер, я всё объясню
01:00
История одного вокалиста
Рет қаралды 2,3 МЛН