No video

Settling the Biggest Await Async Debate in .NET

  Рет қаралды 143,360

Nick Chapsas

Nick Chapsas

Күн бұрын

Join the NDC Conferences Giveaway: mailchi.mp/nic...
Check out my courses: dometrain.com
Become a Patreon and get source code access: / nickchapsas
Hello everybody I'm Nick and in this video I will take a look at one of the biggest await async debates in .NET and try to find the best answer for each usecase.
Workshops: bit.ly/nickwor...
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: bit.ly/ChapsasG...
Follow me on Twitter: bit.ly/ChapsasT...
Connect on LinkedIn: bit.ly/ChapsasL...
Keep coding merch: keepcoding.shop
#csharp #dotnet

Пікірлер: 294
@theonlywallrus
@theonlywallrus Жыл бұрын
Yes, please make a video on ConfigureAwait! Great video, thank you
@iGexogen
@iGexogen Жыл бұрын
I have only one question to "ConfigureAwait", why they didn't make false as default?!))
@Petoj87
@Petoj87 Жыл бұрын
This is one of the worst things about async in legacy code..
@emerynoel567
@emerynoel567 Жыл бұрын
Would love to also get your thoughts on legacy code, specifically .NET Framework 4.7.1
@abdulmoiz3348
@abdulmoiz3348 Жыл бұрын
yes yes, we do need this topic in detail please thank youuu.
@grant_vine
@grant_vine Жыл бұрын
Actually my interest on ConfigureAwait extends to MAUI where they only ever load libs as either singleton or transient (concept of scope is a bit irrelevant on a single user app) but specifically the impact of async on a UI app where a lot of this stemmed from (if my memory serves)
@PanKJ00
@PanKJ00 Жыл бұрын
Unless you have measured this is a hot path, avoiding async/await is a premature optimization in my opinion. Some people think many tiny performance gains will add up. But I think in most cases the bottleneck will be something else and the impact of async/await will be negligible. On the other hand, even if a method simply forwards the async call, losing the stack frame can result in losing time when debugging the code later. Especially if there are many layers of "forwarded async methods", it may be very hard to tell how execution ended up in a certain method. Of course, this doesn't apply to well-tested libraries that we wouldn't want to debug at all. That's why HttpClient doesn't use async/await where possible for example. Another reason is that library code doesn't "know" how it will be used, so it has to be optimized just in case. Note that I have encountered cases where a hot path actually benefited from removing async/await. But these cases are very rare from my experience. And I always had to measure performance before deciding how to optimize such cases anyway.
@itssimplymg4682
@itssimplymg4682 Жыл бұрын
I literally can’t get enough of these videos. And I actually use all this knowledge for my job. Thank you for all your content!
@weluvmusicz
@weluvmusicz Жыл бұрын
Only for your job?
@robertnull
@robertnull Жыл бұрын
ALSO for their job 😉
@stefammagnumfernandesdemen4942
@stefammagnumfernandesdemen4942 Жыл бұрын
Use of async/await for sure. Even though the use of disposable is a big deal, the debugging problem is away bigger than that. Getting a more accurate exception stack is, in the majority of the scenarios, much more important than performance.
@brianm1864
@brianm1864 Жыл бұрын
Great video!! I'm typically in the return Task camp myself. And I'd LOVE a video on ConfigureAwait as I've seen/read different things about whether or not it is needed in APIs.
@thund3rstruck
@thund3rstruck Жыл бұрын
I definitely prefer async/await personally. It's clearer to support and understand, especially on a large team of contributors, and the loss of performance in negligible in the vast majority of use cases.
@noldor__
@noldor__ Жыл бұрын
I used to use Task returns myself and also recommended doing the same to others because it looked slightly more clear and I thought it would make fewer calls in the framework. However, once we struggled to diagnose and troubleshoot exceptions efficiently, I quickly switched to using 'await' everywhere. There is no debate, Task returns are evil.
@precmv
@precmv Жыл бұрын
A video about the pros/cons of Task vs ValueTask would also be great
@nickchapsas
@nickchapsas Жыл бұрын
I already have that
@precmv
@precmv Жыл бұрын
@@nickchapsas Apparently I already watched it :D Your videos are great to point our juniors to. Keep it up :)
@jongeduard
@jongeduard Жыл бұрын
Yep I was thinking the same because curious about that too in this context (being used with async/await versus directly returned). I was thinking about it at the point about Task.FromResult being based on a value type versus reference type.
@philg4116
@philg4116 Жыл бұрын
with better enunciation
@Mark-px3rq
@Mark-px3rq Жыл бұрын
A fair rule of thumb is, if your function returns a value task, don’t do the unnecessary await, as the use of value task suggests the function will be called in a tight loop where the overhead of the state machine will start to matter more.
@mustafaazyoksul1372
@mustafaazyoksul1372 Жыл бұрын
I would love to see a ConfigureAwait video.
@PeterOeC
@PeterOeC Жыл бұрын
Amazing video (again) thanks! 👍 I've had colleagues bashing me for using async/await rather than returning the task. However I think I now have some great arguments for keeping it! - An error shows in the stacktrace where awaited. - Potential gotchas with disposed variables. - Not that much slower. For majority of problems I sit with, performance has less priority than, potentially introducing bugs. The dispose one is particularly scary, cause it might only fail once in a while! I'd go with async/await all the time (unless I have a special case).
@jrhodes69
@jrhodes69 Жыл бұрын
The only benefit of eliding the await is performance gain which I would guess is negligible in the majority of cases. If you get bashed again just turn the question around and ask for benchmarks to prove why eliding the await is beneficial in your use case against the more idiomatic usage of async/await (factoring in the gotchas e.g. exceptions, disposing, additional cognitive load of more junior members of the team understanding the nuance)
@slang25
@slang25 Жыл бұрын
Great video, I've followed the rule of eliding await for "forwarding methods" and middleware, otherwise always await (unless it's performance critical). I like that you are sharing the nuance, not dogmatism
@w4.k
@w4.k Жыл бұрын
The most tricky part about C# is multi threading. It even makes code reviews considerably longer, So i would appreciate more videos on the topic.
@jongeduard
@jongeduard Жыл бұрын
I hope you're not thinking that this video was about multithreading?? Because it really isn't. Because async await is not multi-threading.
@ziio_dj
@ziio_dj Жыл бұрын
Read "Concurrency in C# Cookbook: Asynchronous, Parallel, and Multithreaded Programming" by Stephen Cleary
@SM-tj4jc
@SM-tj4jc 2 ай бұрын
@@jongeduard You are clueless about programming as this joke that calls himself a senior developer but is just a paid book reader.
@abhis9
@abhis9 Жыл бұрын
When I came over from old Fx WebForms days, I was taught to use async/await all the way. Today I don’t know any better 🤓 I would rather be safe and use it all the way to avoid confusion. Dunno how much perf hit would hurt in my typical LoB projects 🤔. And yes, a video about ConfgureAwait would be useful.
@JuliusCesarNL
@JuliusCesarNL Жыл бұрын
A video on ConfigureAwait would be great! I had so many discussions with other developers when or when not to use it. At one point someone claimed that it should be used for literally every async call.. It would be amazing to be able to refer them to your video 😁
@maxime4047
@maxime4047 Жыл бұрын
Configure await is used to refer to the main thread. So important to know when to use it coz it’s a performance impact and deadlock on certain cases. Useful for Maui app for ex but not in backend app.
@FXK23
@FXK23 Жыл бұрын
@@maxime4047 Isn't this standard false in .Net Core (just continue on a free thread)? Thought this was only relevant in .Net framework?
@maxime4047
@maxime4047 Жыл бұрын
@@FXK23 the standard is true to make sure you don’t get dead lock even if in majority you will use false. And configure await true doesn’t mean you get for sure a new thread. It’s just meant that the thread that we continue can be another one
@Moosa_Says
@Moosa_Says Жыл бұрын
I've always used the await way. It seems simple and of course doesn't have using/disposing issue.
@LiaoDrew
@LiaoDrew Жыл бұрын
This is video is SO TIMELY. We're currently implementing async to our entire codebase. THANK YOU!
@JorgeLuisMachadoTorres
@JorgeLuisMachadoTorres Жыл бұрын
We follow a simple rule: if your method it's a one-liner do not use async await, for everything else async await all the way.
@strawhenge5007
@strawhenge5007 Жыл бұрын
Another thing to consider is if your method has guard clauses. If you use the async/await keywords, the guard clauses won't throw until the caller calls await on the resulting task. Usually you would want guard clauses to throw immediately when the method is called. To get around this, you can move the work to another method that does use async/await, then have your main method (no async/await) just contain the guard clauses then call the second method and return it's task.
@hanspetervollhorst1
@hanspetervollhorst1 Жыл бұрын
Yes, please make a Video on ConfigureAwait - or put it in your next course :)
@panagiotislamprakis
@panagiotislamprakis Жыл бұрын
I use both. I return a Task whenever I'm developing a reusable library, and async/await in any other case.
@nickpolyderopoulos3491
@nickpolyderopoulos3491 Жыл бұрын
I have mostly used the version that does not use async and await. But interestingly enough in the last couple of weeks at work we experience some issues around tasks with deadlocks and one of my co workers found out that if we use async and await in the places that deadlock the deadlock disappears. So on the new year we will have an interesting week trying to decipher that. Your video helps shed some light. PS: fun fact that is the second time now where you publish a video that I was searching for. Such a nice coincidence Thank you for your time.
@snekbaev
@snekbaev Жыл бұрын
this also alters the behavior on the calling side, say you have two methods A and B that take some value and do the validation. 'A' after validation does an awaited db query, 'B' similar, but not awaited, just returns the task. Now caller can invoke this methods sequentially and await each, but it can also execute them without awaiting and do the awaiting a bit later. If validation fails for either of those methods then exception will be thrown at different stages: or execution or on await.
@henrysauzande7975
@henrysauzande7975 Жыл бұрын
great insights Nick. I usually use async/await in most cases but I came across some code for writing a proxy application which would forward a client request to another external service, and they were using Tasks but wrapped in Task.Run() I kept wondering why they wouldn't just use async/await watching this video I now understand why that was the case very eye opening
@JoeEnos
@JoeEnos Жыл бұрын
I’d love the ConfigureAwait video, explaining synchronization context. I’ve never felt confident with that.
@jscarle
@jscarle Жыл бұрын
When he says "debugging hangs", he didn't mean that debugging hangs in the IDE, he meant debugging code which causes the application to hang. (Its a subtlety of English.) Because when you debug pause the application, you'll pause at the await of the internal task, not at the await of the calling task.
@davidfowl
@davidfowl Жыл бұрын
👏 Exactly
@Lior_Banai
@Lior_Banai Жыл бұрын
The program with files tests is that the os may cache the file access so second access to the same file will be faster.
@robertnull
@robertnull Жыл бұрын
Nick, I believe you have misunderstood David Fowler's point about exceptions in async methods being "wrapped in Task instead of surprising the caller with an actual exception". What David meant is this difference in behavior: async Task Main() { var task = this.Throw(); // Throw() causes an UnreachableException to be THROWN here while (!task.IsCompleted); Console.WriteLine(task.Exception); // ThrowAsync() causes task.Exception to be populated with an AggregateException that contains the UnreachableException } public Task Throw() => throw new UnreachableException(); public async Task ThrowAsync() => throw new UnreachableException();
@ehvlullo
@ehvlullo Жыл бұрын
I have been awaiting ever since you told us to Nick
@jchandra74
@jchandra74 Жыл бұрын
When I don't need to await something in the middle of a method that returns Task (the last thing it does is call an async method that return a Task but nowhere else), I will not turn that method to async/await, but if anything in the middle of the method does require await (2 or more promise chaining), I will do async/await. Reason is... promise style ContinueWith(...) callback is a bit of a pain. I guess need to add another thing for the async/await which is when you use using statement in the method that calls an async method.
@xavhow
@xavhow Жыл бұрын
Outstanding explanation of returning task vs async-await... I just got into habit of using async-await without actually thinking about the difference. Thank you Nick!
@JamieTwells
@JamieTwells Жыл бұрын
I thought from the thumbnail you were going to weigh up the pros and cons of making API calls using an async vs a sync method like the RestSharp synchronous methods vs HttpClient's async methods. It would be interesting to know what implications for the application both have.
@welrocken
@welrocken Жыл бұрын
You probably shouldn't be calling external API's (or internal, for that matter) synchronously because all that time between the start of the request till the end of the response, you are basically blocking your "thread" (whether that be an HTTP Request Thread for ASPNET.Core or the UI thread for WPF/UWP etc). Async/await is exactly for cases like these, where your thread can not do anything for a given time (reading the file, reading some data from some network etc.), and you do not want your thread (essentially the amount of processing power the CPU/OS gives you) just waiting for stuff.
@stevehoff
@stevehoff 3 ай бұрын
I love the way he says, "your done for" at 9:28
@stevekeith9507
@stevekeith9507 Жыл бұрын
Another greate video Nick! I prefer using await and async, this avoids confusion to other develoopers join after i leave the contract. I guess i can offse the performance elsewhare btw.
@hotdogfun92
@hotdogfun92 Жыл бұрын
Great video, but be careful when benchmarking file access from disk, as you need to take into account any underlying caching mechanism such as those afforded by the operating system. In this case, it's probably not a deciding factor, as only the first call of the method doing the very first read would hit the disk and thus have have a higher latency. Edit: Depending on the size of the file and on how slow of a disk you read from, the initial latency could skew the benchmark result quite a bit (though, I suspect that this is not the case here)
@tomtoups
@tomtoups Жыл бұрын
Very good point. Thanks for mentioning that
@tomtoups
@tomtoups Жыл бұрын
also, that probably explains the relatively high standard deviation
@DOSdaze
@DOSdaze Жыл бұрын
This is exactly what I've been considering in my async heavy applications that run through multiple layers of calls, thank you for the clarity. And yes, a video on ConfigureAwait would be much appreciated. So many things I thought I understood properly until you made a video on it.
@StyleNAofficial
@StyleNAofficial Жыл бұрын
async and await are implementation details. I think letting the caller decide how and when they want to await something is an important case that many haven't brought up. If you're awaiting immediately, you're making a decision for the caller, and therefore the caller would lose that control.
@mightybobka
@mightybobka Жыл бұрын
Be consistent. Await always!
@jongeduard
@jongeduard Жыл бұрын
Async await is a long subject with a lot of details, reading a ton of things on the internet helped me out, including pages shown by Nick in the video. I have also been writing my own async state machine in order to get better understanding of it (after seeing those decompiled examples from ILSpy and Sharplab io) much like I have manually written IEnumerator iterator implementations for same reasons. I can almost recommend other people doing those things. Deep understanding of things you use every day can help a lot. Also a lot of experimenting with deadlock situations and high threadpool load. All to get a better idea what those smart people on the internet are talking about.
@stewartsimpson2236
@stewartsimpson2236 Жыл бұрын
Excellent video as always! A video on ConfigureAwait would be greatly appreciated from my perspective but also going by a lot of the comments posted here! Thanks
@montanomariano
@montanomariano Жыл бұрын
Great explanation! I usually return the task itself when I need to await multiple tasks afterwards with task.whenall, but this gets me thinking there are many other use cases
@avi01224
@avi01224 Жыл бұрын
Great video! Lot of things to learn from you. Yes make video on ConfigureAwait 👍
@Bignickftw
@Bignickftw Жыл бұрын
Thank you very much Nick, great video! You uploaded this video just in time when I was looking at David's guidance, after watching your older video about async await 😄
@stephenyork7318
@stephenyork7318 Жыл бұрын
Yes please do a deep dive on ConfigureAwait
@tafs7
@tafs7 Жыл бұрын
YES to ConfigureAwait video. The write-ups out here are so dense and confusing AF. It's like reading a dry CS textbook explanation.
@mranthonymills
@mranthonymills Жыл бұрын
I generally do return Task because I get suspicious of too much compiler-generated cruft in my assemblies but I'll keep the issue with disposal in mind, thanks!
@iGexogen
@iGexogen Жыл бұрын
I've always used flexible approach like in your final summary, I call it "make Rider happy". Often changing from async to returning tasks contaminating code with many Task.FromResult(...) / Task.CompletedTask, but I am ok with it. In most cases classes that have such "do something sync and then pass through" logic are abstract base classes, or static helpers/extensions.
@asier9332
@asier9332 Жыл бұрын
Great video! It'd be nice to have the ConfigureAwait video :)
@digibrett
@digibrett Жыл бұрын
Just yesterday I accidentally didn't await my DB read and my connection was already disposed, exactly like shown in your video.
@anthony8090
@anthony8090 Жыл бұрын
I typically only use async/await if I either need the result of the task or want to handle the exception within that method. Otherwise, it seems pretty unnecessary to do so. You wouldn't call .ToList() on every IEnumerable you find just because it's easier and to avoid having to enumerate it to an array or list later on, right?
@urbanelemental3308
@urbanelemental3308 Жыл бұрын
I understand it well so I tend to pass through to the underlying task when it makes sense.
@csexton07
@csexton07 Жыл бұрын
One argument is that its more common to use async/await and easier to conceptualize for someone reading your code that may not be aware. I would only use it if performance matters.
@jackp3303
@jackp3303 Жыл бұрын
Fully agree with you Nick, but I would also add - if you a Framework \ library developer - yes, it's much better to return a task, you don't need to show where exactly in your library exception thrown or let user dev to debug your code, but for a feature devs - there is no reasons to avoid async\await. Performance isn't a point where async\await is used, I mean if system is waiting for a second, there is no sense save nanosecond + not sure async operation so often used in loop with billions of iterations.
@PedroPabloCalvoMorcillo
@PedroPabloCalvoMorcillo Жыл бұрын
I've always been using explicit async/await approach. Recently I've used Task approach for extension methods that implement a functional pattern.
@dipendupaul
@dipendupaul Жыл бұрын
One of the other issues that I faced returning Task without an await, in the calling method it does not report anything if I miss await and async, while in the other case, it is reported with green squiggly. Former resulted in some difficult to debug bugs and wasted hours.
@charles_kuperus
@charles_kuperus Жыл бұрын
Yes please make a video on Configure Await. I sort of understand, but I know this would help me and all other software developers to understand.
@benjaminboyle3295
@benjaminboyle3295 Жыл бұрын
In hotpath code, I will write a non-async method that just returns the task (such as reading from a pipe) if it is already completed successfully (as it usually is). But if the task to be returned is not completed, the method will call an inner, async method that awaits it. So you get the benefit of hotpath not using async machinery most of the time, only using to it when the task hasn't completed successfully.
@ChristianHowell
@ChristianHowell Жыл бұрын
Good video... I can say I wasn't surprised when file reading doesn't change much with async since it still has to read the file line by line... I found that even the TPL doesn't make file reading faster... I am careful as to what gets an ASYNC call. I can remember old style async with BeginInvoke...
@emerynoel567
@emerynoel567 Жыл бұрын
As a rule: If I don't need the result, I don't `await` the result.
@robertmrobo8954
@robertmrobo8954 Жыл бұрын
Please get us a video about ConfigureAwait 🙏
@viktoralferov2874
@viktoralferov2874 Жыл бұрын
If you need to use any peripheral device (slow access) - you must always use async/await. In a high load situation async/await works faster, always. imo )
@nickchapsas
@nickchapsas Жыл бұрын
There is no difference in what is being shown in this video. In both cases async await is used. You have to understand that it is NOT faster than the sync alternative. For example something like a Redis cache, will be slower if you use async await, but it will scale better.
@justengineering1008
@justengineering1008 Жыл бұрын
I am curious, what Benchmark measures while a test returns Task? Logically, in tests we have to await result of tested methods. IMHO
@devjonie
@devjonie Жыл бұрын
Your content is among the best, Nick Pleeeease do the video on ConfigureAwait. I just don't get it.
@Petoj87
@Petoj87 Жыл бұрын
Super great video! I usually use without await, i guessed that it would affect the stacktrace but wasn't 100% until now.
@emyrulz
@emyrulz Жыл бұрын
Depends. If the call is part of a complex Api with may levels I prefer returning tasks. Also if the tasks can be combined or the caller has the option to wait for all of them or not. Returning the task is much more flexible from the caller's perspective. Now, in the usual case I prefer to do exactly as you, mostly await and avoid it in trivial forwarding methods.
@anoopsureshnair3564
@anoopsureshnair3564 Жыл бұрын
Thank you for this video. Please make a video about ConfigureAwait
@frankbakker8347
@frankbakker8347 Жыл бұрын
Previously I would return the Task whenever possible. This does mean you need to refactor when adding a second async operation so that is a downside. Because of stacktrace and dispose issues I changed my default to 'async unless'
@StigBrembo
@StigBrembo Жыл бұрын
Yes, please make a video on ConfigureAwait. Let's settle this once and for all.
@bmfdiak
@bmfdiak Жыл бұрын
Thank you Nick for your videos and Courses, they are really useful :) I'd like to see a video about ConfigureAwaiter as well. Happy Holidays!
@marsovac
@marsovac Жыл бұрын
I think the state machine overhead is not what was meant with "performance difference". A task may or may not be awaited if many tasks are chained, and if there is an await in async methods it forces the await even if this task would not be awaited if some other task before it failed. Basically anybody who uses the code could create a performance difference depending on how is he using the code.
@AnGeLuz747
@AnGeLuz747 Жыл бұрын
So amazing topic...,. It could be so interesting discusing about this and the relation with pool starvation & concurrency. Thank you for your time and share your knowelge with all of us, greetings.
@kristianaranda
@kristianaranda Жыл бұрын
Very good analysis with all the pros and cons of both alternatives.
@mytralala6474
@mytralala6474 Жыл бұрын
I always return Task when I can and only use await at the topmost call, but when I have calls to other Async methods, I use awair.
@bsalmeida
@bsalmeida Жыл бұрын
Yes, please make a video on ConfigureAwait! Great video, thank you!
@FredrikLarsson-kt2gw
@FredrikLarsson-kt2gw Жыл бұрын
100% do a ConfigureAwait(false) video!
@allinvanguard
@allinvanguard Жыл бұрын
I like to mix it. The default is to include async await, but sometimes within Linq or fluent APIs, it is nice to elide the async await ceremony for more concise syntax. Sometimes it is also a good thing to be able to modify the call stack by hiding passthrough methods for example. For performance reason alone I would never use it, chances are one line of unoptimized user code amounts to thousands of occurences of eliding async / await in performance drag.
@kyuksel1985
@kyuksel1985 Жыл бұрын
Great video Nick, thank you! I have been using async/await more for the neatness and structure it brings to the code, without realizing the fact that it would create all those stacked up state machines. Will definitely have an impact on my future coding :)
@Orgbrat
@Orgbrat Жыл бұрын
Yes, please make a video on ConfigureAwait!
@michaelinsberg2185
@michaelinsberg2185 Жыл бұрын
Please make a video on ConfigureAwait! Great video, thank you
@salameez
@salameez Жыл бұрын
I think it mostly comes down to whether you care more about what actually and conceptually happens with tasks, or the illusion of the magic async await syntax. Understanding the continuewith syntax (and indeed monads in general) is important if you want to use tasks without async await.
@F4C31355
@F4C31355 Жыл бұрын
ConfigureAwait(false) is the immortal classic for interview. But it would be useful to refresh it for wider audience.
@Pezsmapatkany
@Pezsmapatkany Жыл бұрын
A link for the two articles mentioned would be great in the description. I use direct Task return when possible, but I burned myself previously with the using stuff, so I can understand the other camp too. I never had problems with debugging or stack traces with this approach.
@TrevorJones1
@TrevorJones1 Жыл бұрын
Absolutely do a video on ConfigureAwait let's end the confusion once and for all.
@alfredoquintanalopez2265
@alfredoquintanalopez2265 Жыл бұрын
Yes, please make a video on ConfigureAwait!, thank you
@T___Brown
@T___Brown Жыл бұрын
I only use await if the method uses the object. If it is a forward method... i called a passthrough method, then I just return a task. I would be interested in a performance test of multiple async/await call chains MethodA->B->C->D->E all async version B,C,D,E all being return task and only A awaits. The reasoning is that B,C,D,E would all create a statemachine and add extra overhead.
@Shadow_Play3r
@Shadow_Play3r Жыл бұрын
yes! more info configureAwait please. I learnt a bit about it when using Unity engine and never again. I generally always declare "false" except for rare UI cases
@adam4813
@adam4813 Жыл бұрын
The biggest reason to NOT await the return is the removal of call site control. The caller has no option to await or not, it is forced to. Imagine wanting to create a list of tasks to await later. Adding await at the return would stall out the list creation. By omitting it, you allow the call site to await, but also allow it to defer the await.
@donka86
@donka86 Жыл бұрын
Yes please. Make a nice video on the synchronization context and configureawait
@deeplerg7913
@deeplerg7913 Жыл бұрын
Please link your sources in the description. It really helps.
@jalvrus
@jalvrus Жыл бұрын
My rule of thumb for await vs. return Task is: if it makes sense for the method to be an expression-bodied method, it is a candidate for return Task; else await. There's another difference between using the state machine or not that you didn't mention, and it has to do with what happens when the method throws an exception. If your method throws an exception but does not use an async state machine, the exception is raised in the calling code where the method is called. An exception thrown inside an async state machine results in a faulted task being returned, and the exception is raised in the calling code where the task is awaited.
@ninodolo
@ninodolo Жыл бұрын
Can't wait for the ConfigureAwait video!
@thepetersons1276
@thepetersons1276 Жыл бұрын
Yes, please make a video on ConfigureAwait
@Azcane
@Azcane Жыл бұрын
I always use async await in such functions. It's not just about how Exceptions differ but *when* they're thrown. I often start multiple tasks without awaiting them, doing that later in the function. If an exception is thrown outside of the state machine, the error is thrown in an unexpected place. This code might not work when DoAsync is not an async function because an exception might be thrown when the function is called, not when it's awaited. This alone is a major reason for me to never ever drop async. var task = DoAsync(); try { await task; } catch { }
@arztje
@arztje Жыл бұрын
This was a deep dive I really needed. Thank you for this content.
@GufNZ
@GufNZ Жыл бұрын
Our company just added a rule to our set of analysers to require async, to improve readability on leaf methods that would otherwise have to return Task.FromResult, and to help avoid returning a null Task, tho #nullable enable helps there too. They also suppressed the suggestion that async without any await could be removed.
@theguy9067
@theguy9067 Жыл бұрын
I usually avoid async await when it isn't required like when just forwarding methods. I have noticed it can make debugging a bit more difficult. It seems like always using await would be less of a headache
@entvex
@entvex Жыл бұрын
Yes please make a video on configure await :)
@silentdebugger
@silentdebugger Жыл бұрын
I was hoping to see ValueTask compared in the benchmarks as well as that sounds like the intended compromise between async performance and functionality for tight-loop code
@inzyster
@inzyster Жыл бұрын
Oh yes, a video on ConfigureAwait would be greatly appreciated.
@F1nalspace
@F1nalspace Жыл бұрын
We program a lot in the WPF world, therefore we often need to do work without blocking the UI, so in the view-model we create a core method that returns a Task and then create an async method that awaits that core method. Sometimes we even create a raw method, that is called from the async method as a simple wrapper task, but this is rare. If i ever see async methods called in a chain, i collapse them down to just one async method. Sometimes i prevent the usage of async entirely and use tasks and wait for them instead - it depends on the use-case. But i find it hard to properly secure the methods, so that it wont be called multiple times or can be canceled. Most of the time a simple Interlocked.CompareExchange() and one Exchange() can solve that, but in some cases where multiple calls are actually allowed, that requires much stronger syncronisations.
@billy65bob
@billy65bob Жыл бұрын
I used the task forwarding thing a fair bit. I don't remember what for, I think it was to make overloads that forwarded to the full methods with CancellationToken.None. i.e. DoThingAsync(a, b, ...) => return DoThingAsync(a, b, CancellationToken.None, ...)
What is Span in C# and why you should be using it
15:15
Nick Chapsas
Рет қаралды 253 М.
The Free Way to Create Awesome PDFs in .NET
12:45
Nick Chapsas
Рет қаралды 21 М.
WILL IT BURST?
00:31
Natan por Aí
Рет қаралды 40 МЛН
Just Give me my Money!
00:18
GL Show Russian
Рет қаралды 950 М.
Throwing Swords From My Blue Cybertruck
00:32
Mini Katana
Рет қаралды 10 МЛН
That's NOT How Async And Await Works in .NET!
12:25
Codewrinkles
Рет қаралды 21 М.
I Feel Bad For New Programmers
19:12
ThePrimeTime
Рет қаралды 436 М.
HTTP Polling vs SSE vs WebSocket vs WebHooks
22:22
ByteVigor
Рет қаралды 4,7 М.
Await Async Tasks Are Getting Awesome in .NET 9!
9:24
Nick Chapsas
Рет қаралды 93 М.
Don't throw exceptions in C#. Do this instead
18:13
Nick Chapsas
Рет қаралды 257 М.
8 await async mistakes that you SHOULD avoid in .NET
21:13
Nick Chapsas
Рет қаралды 312 М.
What are record types in C# and how they ACTUALLY work
15:36
Nick Chapsas
Рет қаралды 120 М.
"Stop Using Async Await in .NET to Save Threads" | Code Cop #018
14:05
Don't Use Polly in .NET Directly. Use this instead!
14:58
Nick Chapsas
Рет қаралды 59 М.
50 BILLION MESSAGES PER DAY WITH 32 ENGINEERS | Prime Reacts
14:58
ThePrimeTime
Рет қаралды 513 М.
WILL IT BURST?
00:31
Natan por Aí
Рет қаралды 40 МЛН