Тёмный

8 await async mistakes that you SHOULD avoid in .NET 

Nick Chapsas
Подписаться 307 тыс.
Просмотров 313 тыс.
50% 1

Опубликовано:

 

29 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 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!
@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."
@FatihTurkerFatih
@FatihTurkerFatih Год назад
Very well done
@nickbarton3191
@nickbarton3191 3 месяца назад
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?
@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 : ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-I4cnX_odC1M.html . continuewith is good if you are not awaiting the task result.
@Daniel-yl5fi
@Daniel-yl5fi Год назад
Hi Nick, How do you pass cancellationToken to Task.WhenAll()?
@CS-eh8eo
@CS-eh8eo 3 года назад
Nice content, do you know anyone similar who does kotlin ?
@soho1080
@soho1080 3 года назад
A lot of material presented here w/o any backing case! No good.
@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!
@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
@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.
@ruslanbocharov
@ruslanbocharov 4 года назад
catch (TaskCanceledException) when (cancellationToken.IsCancellationRequested)
@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.
@rishvaksreshta9464
@rishvaksreshta9464 2 года назад
Nick didn't really give a reason why once async should always be async. Can someone explain?
@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.
@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!
@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?
@user-tk2jy8xr8b
@user-tk2jy8xr8b 2 года назад
Making Task F() { using var g = G(); return H(g); } instead of async Task F() { using var g = G(); return await H(g); } is a straight way to get a disposed object accessed
@josephmoreno9733
@josephmoreno9733 2 года назад
In that specific case, the async/await must be used or pass a delegate to G() inside the task (or call the G() directly in the task). Always is better use the using keyword inside the task. I think the async/await overhead can become significant. However I return task if and only if certain 'rules' are met: * The method that returns the task has the same type of returned task or is a task without result. * The method that returns the task only executes that statement. * The method that returns the task executes that statement at the end and is the only asynchronous call one but, the parameters for this task must not be invalidable (collectable or disposable or mutable outside the task) in the lifetime of the method execution, that includes delegates or tasks (which should be awaited inside the returned task) as parameters. * The method that returns the task must uniquely choose from a finite set of tasks of the same type which one to do based on runtime conditions. Any violation to this 'rules' implicates use async/await.
@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.
@Reza-zt4sx
@Reza-zt4sx 4 года назад
Hi Nick, thank you for your hard work and knowledge sharing here. It would be great if you elaborate about best practices on error handling. It is one on the wide and most useful topics. There are a lot of videos and resources on the internet, but still some of the ideas behind them are not clear for me. Thanks.
@eparizzi
@eparizzi 3 года назад
Another confusing topic you should have addressed is the .ConfigureAwait(Boolean) method on Task. Recent DotNetAnalyzers will prompt you to call this method on every awaited task by default. It's not always clear to people whether they can ignore that rule.
@EvaldasNaujikas
@EvaldasNaujikas 2 года назад
Well, for .NET Core you don't need to use it anymore, unless you're writing a library, because Core itself is not using SynchronizationContext anymore.
@menyus777
@menyus777 2 года назад
@@EvaldasNaujikas *ASP.Net core
@tarquin161234
@tarquin161234 4 месяца назад
Disagree on ContinueWith. Where I have further processing on a Task, I find it convenient to be able to do that in a temporary scope so as to not introduce temporary variables into the outer scope (like you've done). Like chaining promises in javascript, it is very clean and simple. I don't see any convincing arguments here. To me, you've made the code worse by introducing a new variable (finalNumber). If you're going to say "Don't do something", you're going to need to say why.
@canabale
@canabale 27 дней назад
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.
@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?
@Jose67898
@Jose67898 2 года назад
Hi! Can you speak a little bit faster? (Fortunately everyone's mother tongue is english in the world.)
@adriangodoy4610
@adriangodoy4610 3 года назад
I don't see the benefit of async awayt outside UI at all. Most programers await all the calls even when not needed, where's the performance benefit of that? Nobody talks about how or why async await is better and where the performance gains come from. Actually as far as I seen on the industry maybe we have worst performance because async await
@nickchapsas
@nickchapsas 3 года назад
There actually many benefits (in my opinion more important than the UI use case) when using async await. It mainly has to do with IO operations that no longer have to lock your thread and wait synchronously for something like a database call to complete to move on. You can simply await the call and then that thread will go and do something else instead of wasting CPU clock cycles and when the database cal returns then the (or some) thread returns to continue the work. This allows your app to scale better because you can do more stuff with less resources.
@adriangodoy4610
@adriangodoy4610 3 года назад
@@nickchapsas I mean a problem on how people use it, as from the main to the end every async call has await on it. So the free thread only can wait for it. I've seen everybody using it but nobody taking advantage of that. The free thread can only wait because from main every call has await next to it
@adriangodoy4610
@adriangodoy4610 3 года назад
@@nickchapsas In fact I had pr's not approved for calling 3 non dependent async methods and awaiting them afterwards. And I had to make a demo project showing that that's exactly the use case for async methods
@doc8527
@doc8527 3 года назад
@@adriangodoy4610 that's how I understand the thing about async\await, if you have dependency on that async call, then do async and then await so you can do whatever you want with the data later on. Otherwise just use regualr function without the need of using that syntax
@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.
@GGGStalker
@GGGStalker 11 месяцев назад
you should add that cancellationtoken is breaking the http pipeline, thus it's valid to use everytime you async
@Chiramisudo
@Chiramisudo 2 года назад
1:08 says "without further ado" and immediately contradicts himself. 😅
@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?
@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.
@codingwithgyver1637
@codingwithgyver1637 3 года назад
Thank you for this video, now I know that async/await in our codebase is really messy.
@DummyFace123
@DummyFace123 Год назад
That async task delay in a gamechanger for task cancelation, used to have to loop 😩
@jradplowman
@jradplowman 2 года назад
I see so many of these in our legacy code base... Looks like it's time to refactor 😝
@superhussein
@superhussein 2 года назад
nobody should use await and async because c# doesn't support second order functions!
@Jandalf430
@Jandalf430 2 года назад
"In netcore there is no context where you cant wait a task". What about the Startup class?
@AljRest
@AljRest 6 месяцев назад
Thank you so much for this video it has been enlightening!!
@pthanos
@pthanos 3 года назад
Yeah..no async in a vb com+ service bus written in 2007..
@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!
@ziia0528
@ziia0528 2 года назад
9:20 how a IValueConverter method could be async?
@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
@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
@fullmoonyeah1180
@fullmoonyeah1180 2 года назад
if an async operation doesnt return any result, just use fire forget. is it correct?
@mAcCoLo666
@mAcCoLo666 4 года назад
I think the possibility of a deadlock is much more dangerous than wasting one more thread. Deadlocks are damn hard to spot and debug. Threads are hopefully quite cheap to create (and you can always revert them back if your performance really suffer from it)
@charrystheodorakopoulos4843
@charrystheodorakopoulos4843 3 года назад
Κάνε ένα και για την ConfigureAwait για το λαό σου.
@lordicemaniac
@lordicemaniac Год назад
at 14:25 you returned Enumerable.Empty() in async method, shouldn't your rather return await Task.FromResult(Enumerable.Empty...) ?
@anathimatshaya9909
@anathimatshaya9909 Месяц назад
Looks like I can't use Async with ref params🤔
@anathimatshaya9909
@anathimatshaya9909 Месяц назад
Had to use tupel
@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.
@acidhauss7018
@acidhauss7018 2 года назад
The static async method is really clever, had that problem for years
@GazziFX
@GazziFX 2 года назад
7:35 why you awaiting this ValueTask you can just `return new ValueTask(numberToAdd * 2);`
@info4gourav
@info4gourav 4 года назад
I really like nick and raw coading's video...
@FarukLuki111
@FarukLuki111 2 года назад
Thank you for this video! Question: ist the cancellation token global for the whole application? Imagine having a windows service that just got the „shutdown“ command! Wo alle cancellation tokens fire?
@ArtemisChaitidis
@ArtemisChaitidis 2 года назад
I disagree with your async void is bad... any unhandled exception will crash your process, and you dont want something to crash without really knowing that it happened as you initially demonstrated. In that case you implement a try catch, which will still work the same way with async void as async Task.
@mateusferraz4808
@mateusferraz4808 Год назад
@nick You are very nice Guy, I am developer some years, but i am learning to much with you about .NET. Tks
@Mooncat25
@Mooncat25 Год назад
Your video is good. But I want to add to the second point which is about `async void`. IMO it really depends on what you are doing and what is the limitation. More specifically, if you are working with APIs that are not thread-safe, and thus you can't use `Task.Run`, then using `async void` is fine, since `await async` without using `Task.Run` runs in the main thread (which is why the exception in the example crashed the whole process). I guess this happens more likely when working with game engines whose APIs are most likely not thread-safe.
@jaanrett
@jaanrett 2 года назад
In a scenario where you override a method that does not have async in the signature, how do you await without an async void?
@nickchapsas
@nickchapsas 2 года назад
You can't
@jaanrett
@jaanrett 2 года назад
@@nickchapsasI had written a game for Xbox live indie games back in 2010 before async/await with c# and xna, and that was probably around the time I also stopped working professionally with c#. After about 10 years I wanted to get back into .net and c# and thought I should port my game to monogame, and uwp to make it work on both windows and newer Xboxes. That's where I had to figure out this new to me async/await. I struggled the most with this one aspect, everyone telling me to avoid async void, and not knowing a better way to integrate async apis into a framework that doesn't support it, specifically update/draw functions from the monogame/xna. Anyways, it would be great if you made a video about that kind of real world integration issue. In any case, I enjoy your content and your knowledge. Keep up the good work.
@erikzamecnik4914
@erikzamecnik4914 2 года назад
Once you go async always async is a mistake?
@minhgiangho1410
@minhgiangho1410 4 года назад
So, prefer async over task? Or prevent async over task? Take a look at this video ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-My2gAv5Vrkk.html
@nickchapsas
@nickchapsas 4 года назад
There is a trade off but I would personally go with David Fowler’s suggestion
@gp6763
@gp6763 Год назад
@Nick Chapsas Await is pausing the current process until the resolution of the awaited task. This is not only a question of state machine allocation. By immediately awaiting every tasks you're making your code work synchronously. Consider this code : Var taskOne = doStuffAsync(); Var taskTwo = doOtherStuffAsync(); Await taskOne; Await taskTwo; Doing like this task one and task two are being executed simultaneously. If you're immediately await the functions you are in fact executing them one after an other, aka synchronously.
@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.
@ryanhaney
@ryanhaney 2 года назад
The first example wasn't even possible in older versions of .NET because async Main wasn't supported.
@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?
@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.
@bongbui
@bongbui 3 года назад
hi Nick, when use EF Core with action Insert, Update, Delete data, we should pass CancellationToken? Thank you
@MINDoSOFT
@MINDoSOFT 3 года назад
Love the information shared ! Thank you Nick. Learned a lot from the "Always pass the CancellationToken" and the "Don't sync over async in constructors" !
@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?
@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 ...
@erikparso1760
@erikparso1760 3 года назад
Not using continueWith is more recommendation than mistake. I personally prefer continueWith with functional programming.
@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?
@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.
@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.
@mattc4153
@mattc4153 2 года назад
Can’t await in a constructor
@TechySpeaking
@TechySpeaking Год назад
First
@lollo4711
@lollo4711 3 года назад
COOL: Enumerable.Empty .. I didn't know
@i_fuk_religion
@i_fuk_religion 10 месяцев назад
The cancellation token part is sic....
@anthony8090
@anthony8090 2 года назад
async all the way != await all the way if you don't need the result or want to handle the exception there is no benefit or need to await it
@unnilunnium101unknown8
@unnilunnium101unknown8 Год назад
Which IDE is he using?
@Mauricio.Solorzano
@Mauricio.Solorzano 2 года назад
I really liked the way to pass a factory to a constructor that you need to make async. Very enlighting. Thank you Nick!
@rik0904
@rik0904 3 года назад
wait I can do every thing async EVERYTHING
@Roudter
@Roudter 2 года назад
Great stuff...Very useful insights...Thank you.
@ryanhaney
@ryanhaney 2 года назад
Also, async void isn't bad, it just works differently.
@anilkumar8753
@anilkumar8753 Год назад
I think one can learn entire Go in lesser time than the C# async/await itself :)
@erikterwiel2839
@erikterwiel2839 2 года назад
Please slow down.
@Zapo9668
@Zapo9668 2 года назад
Very cool video
@AzureFullstackDev
@AzureFullstackDev 4 года назад
good stuff from 00:01 ;)
@troncek
@troncek 2 года назад
What's the IDE he's using?
@nickchapsas
@nickchapsas 2 года назад
JetBrains Rider
@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
@BlazarVision
@BlazarVision 3 года назад
An excellent video going over Async. Lots of great information here!
@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)
@parsamehdipour2473
@parsamehdipour2473 8 месяцев назад
Nice🔥
@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
@JohnWilliams-gy5yc
@JohnWilliams-gy5yc 3 года назад
Brilliant gotchas picked. Very concise and understandable demo sequencing. You are a very good teacher, sir.
@Any1SL
@Any1SL 2 года назад
Steven Cleary has a few amazing blogs on this.
@RobDugas123
@RobDugas123 4 года назад
How do you solve an await in a get; set; private string MyCarResult; private string MyCar { get { return MyCarResults; } set { MyCarResults = value; await someFunction(MyCarResults); } }
@nickchapsas
@nickchapsas 4 года назад
You turn MyCar into a field and you create proper async setter. Your setter should just set the value and not really do any other stuff unless it's a domain model in which case just move it to a separate method and then set the field value.
@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
@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!
@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.
@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.
Далее
What is Span in C# and why you should be using it
15:15
Ко мне подкатил бармен
00:58
Просмотров 92 тыс.
Трудности СГОРЕВШЕЙ BMW M4!
49:41
Просмотров 1,6 млн
That's NOT How Async And Await Works in .NET!
12:25
Просмотров 23 тыс.
Await Async Tasks Are Getting Awesome in .NET 9!
9:24
Being Competent With Coding Is More Fun
11:13
Просмотров 82 тыс.
Settling the Biggest Await Async Debate in .NET
14:47
Просмотров 144 тыс.
What are record types in C# and how they ACTUALLY work
15:36
The Logging Everyone Should Be Using in .NET
15:34
Просмотров 70 тыс.
Ко мне подкатил бармен
00:58
Просмотров 92 тыс.