Тёмный

"Stop Using Async Await in .NET to Save Threads" | Code Cop  

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

Until the 20th of May, get our new Deep Dive: Microservices Architecture course on Dometrain and get the Getting Started course for FREE!: dometrain.com/course/deep-div...
Become a Patreon and get special perks: / nickchapsas
Hello, everybody, I'm Nick, and in this video of Code Cop I will take a look at a newsletter post on LinkedIn that contained some pretty bad advice regarding Lists, memory and async await!
Workshops: bit.ly/nickworkshops
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: github.com/Elfocrash
Follow me on Twitter: / nickchapsas
Connect on LinkedIn: / nick-chapsas
Keep coding merch: keepcoding.shop
#csharp #dotnet #codecop

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

 

12 май 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 233   
@antonmartyniuk
@antonmartyniuk 19 дней назад
Stop using your PCs, save the electricity
@futurexjam2
@futurexjam2 19 дней назад
:)) I will loose also my private jet :)
@testitestmann8819
@testitestmann8819 19 дней назад
Avoid bugs - stop writing code
@DemoBytom
@DemoBytom 19 дней назад
To be fair, my PC is my main space heater as well.. So I kinda am saving electicity while using it? :D :D :D
@xorxpert
@xorxpert 19 дней назад
stop using electricity, use solar energy
@discbrakefan
@discbrakefan 19 дней назад
Yeah get a Mac 😂
@klocugh12
@klocugh12 19 дней назад
"Don't leave your house, you might get hit by a car"
@POWEEEEEER
@POWEEEEEER 16 дней назад
"Don't stay in house, the ceiling might collapse on you"
@eramires
@eramires 7 дней назад
@@POWEEEEEER "Don't make a comment, you might get a response you don't like."
@EikeSchwass
@EikeSchwass 19 дней назад
We actually had thread pool exhaustion in production. The reason was an Oracle-DB with EF (Core) paired with async/await. Oracles provider doesn't support true callbacks and just blocks threads, until the database operation completes (basically Task.Result under the hood). So although async/await is not the issue per se, in combination with that oracle garbage it caused massive issues for us
@lizard450
@lizard450 19 дней назад
I also ran into an issue with this when working with sql lite a few years back. Maybe I'll fire up the old project update the packages and see if I still can get the issue.
@VINAGHOST
@VINAGHOST 19 дней назад
I thought only sqlite has this problem
@JacobNax
@JacobNax 19 дней назад
That also happened to us with StackExchange Redis due to a bug x)
@eddypartey1075
@eddypartey1075 19 дней назад
​@@JacobNax how do u face this issue with StackExchange Redis? I'm curious
@Rick104547
@Rick104547 19 дней назад
And this ppl is why you shouldn't block in async code. If it was implemented that way you would indeed be better off without async await.
@maacpiash
@maacpiash 18 дней назад
11:08 "...David Fowler, who's basically, God..." Truer words have never been said 🙌🏽
@jasonenns5076
@jasonenns5076 10 дней назад
Calm the blasphemy down.
@gnack420
@gnack420 2 дня назад
​@@jasonenns5076 sorry, let me correct: "David Fowler, who is literally God"
@NickMaovich
@NickMaovich 19 дней назад
"Seed with random number" while there is 420 will never not crack me up :D
@tymurgubayev4840
@tymurgubayev4840 19 дней назад
normal brain: List galaxy brain: List (old brain: ArrayList)
@mattyward1979
@mattyward1979 7 дней назад
Genuinely used List for a weird edge case of wonky json data being spat at a UI, but never a List... ever... EDIT to add - I removed it pretty fucking fast when I realised that our serialisation method opened up a MASSIVE security hole where any caller could deserialise any object on our server, and execute code in it's constructor...
@Chainerlt
@Chainerlt 19 дней назад
TLDR; always use "using" with disposable objects when you can (unless you're doing something very fancy and you're fully aware how to handle these specific cases). The idea behind "using" with disposable objects is to prevent memory leaks in several ways: 1 - people not always know what is needed to be done for a proper object cleanup, and even if they think they do, because maybe they looked inside the source for that particular disposable class, it might change in the future. In the example of sql connection it might no longer be enough to call Close(), because you're are not aware that package developers added something more in the dispose method. 2 - people might not be aware of things which can throw exceptions before they manually clean the object, thus it can lead to memory leaks with dangling handles to unmanaged resources and etc. 3 - properly implemented dispose pattern also makes destructor to call dispose method, thus GC will call it anyway for undisposed object and this can result in some unexpected behavior (this depends more on the implementation and ownership of disposable objects).
@DevelTime
@DevelTime 19 дней назад
"The idea behind "using" with disposable objects is to prevent memory leaks in several ways:". It is much better to say "resources", because once you start associating disposing with memory, you are shortcuting its actual purpose.
@mk72v2oq
@mk72v2oq 19 дней назад
The biggest flaw is that C# does not indicate disposables in any way. You need to memorize which classes are disposable. Compiler does not produce warnings if 'using' is omitted.
@protox4
@protox4 19 дней назад
@@mk72v2oq There has to be an analyzer that does that already.
@billy65bob
@billy65bob 18 дней назад
It's less about leaks (the GC will get around to it eventually). it's more with dealing with unmanaged resources (i.e. things the GC isn't aware of, such as Drawing.Bitmap), and depending on what you're doing, returning resources when you're done (e.g. SqlConnection, Mutexes, File Locks, etc), or finalising things where appropriate (e.g. MVC uses it to write the closing tags for HTML renders, Streams to Flush). The latter 2 are critical; for the former, improper disposal can and **will** make your app stall indefinitely if there is insufficient GC pressure, and not doing the latter will make you output garbage. Also if you want some inspections, I believe Roslynator has several around IDisposables to augment the ones in VS itself.
@alfflasymphonyx
@alfflasymphonyx 18 дней назад
@@mk72v2oq this is absolutely right. There ought to be an indication at least at compile time if the object calls dispose somewhere in the code. And to be honest, if a class uses un managed memory, it is not my responsibility to clean it! The destructor of the class implementing the IDispose should free the memory it used. The IDispose should force the use of dispose method in the class. Using the class, I should not need to use using. I do not care what and how things are made inside that class really.
@pali1980
@pali1980 19 дней назад
in addition to the issues with point 1), there would be no boxing involved when storing strings inside of a List as strings are reference types (even though they do have some behaviours from value types), so even that example does not work
@ErazerPT
@ErazerPT 19 дней назад
Amusingly, the MS .Net 8/9 page suggests you DON'T use ArrayList but List. My guess is, a lot of people used List because they don't know ArrayList exists, and i won't hold it against them because IT IS counter intuitive, and now the .Net team is simply doing all work going forward on List and ArrayList will be left as is.
@metaltyphoon
@metaltyphoon 19 дней назад
You don’t use ArrayList because it is not generic, plain and simple.
@ChristopherJohnsonIsAwesome
@ChristopherJohnsonIsAwesome 19 дней назад
I only used List once when I wasn't sure what I was getting back from reflection. That was before I learned better ways to handle that situation.
@Ivolution091
@Ivolution091 19 дней назад
Thanks for referencing to David Fowler's AsyncGuidance article!
@Drachencheat
@Drachencheat 19 дней назад
When the advice is so outrageous that your pullover transforms into a t-shirt
@parlor3115
@parlor3115 19 дней назад
That's actually welcome since it's getting really warm in here
@maacpiash
@maacpiash 18 дней назад
Watching the video from Australia, I appreciate his t-shirt being transformed back into the pullover.
@CharlesBurnsPrime
@CharlesBurnsPrime 18 дней назад
I use IEnumerable often, for the specific case of executing SQL with Dapper for which the nature of the results are not known at compile time, but I have never seen a List outside of deep library corner cases.
@bslushynskyi
@bslushynskyi 18 дней назад
I used List in scenario where list was used as bucket for various objects which stored some results of various part of application and for some specific operation looped through that list checking type and perform final calculations accordinly. It was back in Window Forms and C#4.0, I think. However, I would rather say that I did it this way because I didn't know better one back than.
@billy65bob
@billy65bob 18 дней назад
I actually have used List before. I was converting some old codefrom ArrayList to List so I could actually understand what was going on, and there were collections that were being used for 2 or more distinct and completely contradictory types. I didn't want to deal with that at the time, so ArrayList -> List it was for those. On the other hand, that refactoring also revealed about a dozen bugs before I even got around to the changes I had wanted to do, lol. I have also used it in the form of Dictionary when I was building a thing to load a configuration file, and use said configuration to build a completely arbitrary nested data structure. The result of which was serialised into JSON to send off elsewhere.
@mattyward1979
@mattyward1979 7 дней назад
Yeah seems one of the corner cases where it's valid. But generally, within a C# closed system that isn't shitting bad data across the wire, I really can't think of a good reason for it!
@DevLeader
@DevLeader 19 дней назад
I suspect this is written by AI primarily, for three reasons (there are probably more): - the advice on loops is outdated and those optimizations are within last few years - the advice overall is kinda sloppy, kinda just... Stuff that you can say with confidence and people might agree. - The word "judiciously" is extremely uncommon, unless you're using an LLM Nothing wrong with using AI to support your writing but... You still need to read it. I don't know who wrote the newsletter, and I mean nothing negative by commenting, but I'd suggest more thorough investigation/proofing when using AI tools.
@thebluesclues2012
@thebluesclues2012 12 дней назад
Spot on, shows the poster doesn't code, so it's junk, there's gonna be more of these junky articles.
@eramires
@eramires 7 дней назад
I am so tired of the AI trend. Everything in my office now people say: oh chatGPT can do that. Geeeez can people be MORE lazy? ffs no one wants to do stuff anymore. :(
@jongeduard
@jongeduard 19 дней назад
I would even say, the whole point of async await is that it does NOT cause threads to block. For that same reason it's designed to PREVENT thread pool starvation. So it's literally the opposite of what they wrote there. If you still experience problems, it's a sign that you do things wrong. A possible cause is calling GetAwaiter().GetResult(), Result or Wait in your code, which causes multiple threads at the same time to hang.
@itsallgravy_9437
@itsallgravy_9437 19 дней назад
List = NO! Autocomplete/refactoring will take care of the hassle of creating the new class(es)...use it. Create that class with a name that makes sense, then populate that nice new reference type with properties as you need...
@dgtemp
@dgtemp 18 дней назад
I have used the 1st point in one of my endpoint which basically is a lookup fetched dynamically based on params. Previously I had used EF Core but as you know it doesnt have generic entity types and the code is also a mess with a lot of if else statements / switch statements. I switched to dapper with sqlbuilder and revamped the endpoint to generate query dynamically based on params with return type as object (obviously because we dont know what the return type of the fetched lookup is). Also not to mention I have a table which has all the lookup entries and their respective columns to be fetched. So that is also dynamic and can be changed however you like. Hence the IEnumerable
@ryan-heath
@ryan-heath 19 дней назад
Actually ... using (...) is preferable over manually disposing objects. In case of exceptions, the scared unmanaged resources (for instance, db connections) are given back or closed, to be used by other waiting tasks.
@ThomasJones77
@ThomasJones77 19 дней назад
Using List instead of List when you know only strings will be stored doesn't make sense. However, there are many cases where List or object[] makes perfect sense in .NET right now, and in fact there's no other way at times. It seems some devs deal with a limited amount of code paths/scenarios to say they can't *ever* see any usage beyond old code, or have never used it. Just off the top of my head, if you have any code that needs to collect data to invoke various methods via reflection, List is a must for collecting values to pass into those methods. There are other scenarios where one may build a specific serialization background service to conform objects for audit or storage where strongly typing the class makes no sense. There are several other scenarios that make sense off the top of my head also, but I'll move on. List should only be used when it makes sense. It should never be used when the type is known, or if an interface or base class type can be used for differing types. Obviously, boxing value types *unnecessarily* should be avoided.
@manilladrift
@manilladrift 19 дней назад
Hot take: If you're using List, it's because you lack the technical expertise required to build a solution in a maintainable, type-safe way. Honestly just a skill issue on your part.
@ThomasJones77
@ThomasJones77 18 дней назад
@manilladrift Real Hot Take on your so-called hot take: BWAHAHAH. Absolutely wrong @manilladrift . If you make comment that implies "there is *never* a reason to code in such a way" then it's you, *honestly it's you*, who not only lacks technical expertise, but you also lack coding experience. While object[] can often be used instead of List there are scenarios that *a developer with actual technical expertise* will recognize the latter is better. There's a reason reflection invocation calls to methods use an object[] parameter. It's because methods have parameters of any number of types. Now, follow what I'm about to say so you can gain some knowledge. If you have an object[] in .NET's method invocation reflection call because the parameters can be of mixed types when invoking a method, SCENARIO 1: if you at *run-time* need to collect data of varying types for a method invocation that itself is also determined at run-time, which has an object[] parameter in addition to other parameter types, then *List* is perfect for that scenario. There's other details about the invocation that solidifies that as being perfect too, but what I mentioned sufficiently demonstrates it as preferable if you understand. That scenario is for a system that collects live data as a conversation is being monitored for specific words. Various word are connected to various types, and those types are collected in real-time. Various word combinations then trigger the need to invoke various methods determined at runtime that have varying parameters counts & types, passing in various metadata types as individual parameters. Those methods then do their work providing valuable info for speakers in the conversation. A complete success. If you have in your mind "*nEVeR* uSe *List* because sOMebOdY said 'aLWayS bAd'" then you'll probably try allocating an object[] with a probable size and resizing object[] as needed like the code behind List would similarly do, instead of simply using List, which is optimized already, to collect the data as it came in. Using *List* to collect that data of varying types as it came in would be the proper approach for that scenario. Your assertion @manilladrift, with just one scenario of many, is wrong. Whether you think a particular design is good or bad, extreme or otherwise, there are proper scenarios in good designs and bad designs where using List is proper for the particular design in use. *Understanding that comes with maturity @manilladrift.* Your reasoning is why people say silly things in YT videos like "there's *NEVER* a good reason to use async void or Task.Wait." While the use cases may be extremely limited, saying "never" simply demonstrates one's lack of expertise & experience. Your comment has exposed yours. Good day.
@manilladrift
@manilladrift 18 дней назад
@@ThomasJones77 I'm sorry, I disagree completely. I believe there is always a smarter, more type-safe way to represent diverging types by aggregating common or expected traits into separate type definitions. Using a List is simply a bad design decision that shows the developer is simply unable to come up with a smarter solution. Again, it's a skill issue.
@flow3278
@flow3278 18 дней назад
@@ThomasJones77 you have varying types and you dont know when and it what order they occur, but as a programmer you still know what kind or pool of types you could expect, right? so cant you just create an interface like ICollectedData or something that all known types implement? even if the types dont share a common functionality defined in the interface, wouldnt an empty interface still vastly improve the code readability?
@ThomasJones77
@ThomasJones77 18 дней назад
@@manilladrift As an exercise, rewrite the .NET method invocation code (*MethodInfo.Invoke(...)*) to be strongly typed only, eliminating object and object[]. Just something as basic as that demonstrates that it is you who lack the skill and experience. There are simply instances where things do not need to be strongly typed as you insist. You say it's bad design and the developers of .NET should have come up with something better, but you can only make such an assertion if your skill and experience level with various coding scenarios are limited. The use of List for collection to populate various parameter types of various methods that are determined at runtime is just ONE example of many.
@David-id6jw
@David-id6jw 19 дней назад
@6:00 - Just a note. I looked at this when you did your last video on loop performance, but my own benchmarking does not show any benefit to uplifting the size of the array/list/whatever instead of just using it in the for loop directly. SharpIO does show that there are more compiled instructions (something like 5 instructions out of 20, IIRC) if you leave the .Count or whatever in the loop function, but performance was nearly identical - at most a 0.5% difference. I suspect it gets optimized out once it runs a few times. There's also the question of which one better allows eliding bounds checking. In theory both should, but I've encountered some indications that uplifting the count sometimes loses that optimization (or at least didn't used to a few versions ago). EDIT: And Stephen Toub was in an interview video that just got uploaded an hour ago, and mentioned a tool called disasmo which gives you the actual final assembly output of the JIT. Using that, I see that there's only a one-line difference between the lifted and unlifted versions of the loop. That difference is just assigning the list size into a different (additional) register, which leads to a slight shuffling of which registers are used in the rest of the code. The loop itself is identical, aside from the names of the registers. So lifting the size of the list out of the for loop does basically nothing. EDIT 2: Also also, just switch to a span if you need performance. The same benchmark is twice as fast as the default one if you marshal the list as a span. The number of assembly instructions for the loop section is halved (5 vs 11). Basically, lifting the size accessor out of the loop provides no performance benefit, and if you really need extra performance, switch to a span.
@Nobonex
@Nobonex 19 дней назад
0:58 If only I'd been so lucky haha. Currently maintaining a codebase where the previous developer didn't seem to like type safe languages. Objects and dynamics everywhere for no apparent reason.
@jfftck
@jfftck 19 дней назад
Sounds like a JavaScript developer.
@makescode
@makescode 19 дней назад
The further irony of the first example is that it talks about the potential problems with value-type boxing and then uses "List" as the better alternative.
@tlcub4bear
@tlcub4bear 17 дней назад
12:47 what magic did you use to show the code underneath?
@bankashvids
@bankashvids 18 дней назад
This was a good one. Thanks!
@username7763
@username7763 19 дней назад
I didn't know that about the async / await creating a state machine and a little extra execution time between examples. To me, logically the returning a task and awaiting on it are exactly the same and I assumed the compiler created the same code for both. I knew there was some state machine logic with async but I assumed only when there were multiple awaits. Very interesting! I learned something new here.
@alexandernava9275
@alexandernava9275 19 дней назад
I have only seen List for not knowing type. Though I will say, I would lean generics if you don't know the type.
@davidmartensson273
@davidmartensson273 18 дней назад
I have only used the likes to List when deserializing unknown list data, or in some adhoc code where I needed to have lists of unrelated types, but even in those cases I usually find better solutions. And I do not really recall any colleague ever using List without a good reason and understanding of the implications.
@mattyward1979
@mattyward1979 7 дней назад
" deserializing unknown list data" - from experience, this is a massive security hole that I'm glad you resolved :)
@davidmartensson273
@davidmartensson273 6 дней назад
@@mattyward1979 In this case its not data from external sources but rather for some generic debugging or as I mentioned, adhoc parsing to easier identify what types I do need to map out the correct type of objects. In production code I would not trust that kind of code, even without the security problems :)
@AtikBayraktar
@AtikBayraktar 18 дней назад
12:50 we don't have to manually dispose our injected dependencies including DbContext? built-in dependency container does that for us for each object lifetime, am I right?
@mattyward1979
@mattyward1979 7 дней назад
Depends what the lifecycle of your dependencies are. If you have a singleton that hosts your DBContext, you may have introduced a memory leak unless you manage it internally If you're using something like Castle or .NET DI containers, PerWebRequest/Transient will tidy up anything that no longer has a dependency (typical garbage collection) If you have a dependency in that chain that is a singleton, it will remain in memory and always be injected into those new instances
@ismailosman5048
@ismailosman5048 4 дня назад
List ....... Never
@_tanoshi
@_tanoshi 19 дней назад
i actually had to use List quite a bit when dealing with some quirky stuff in WPF... but that was because they do not support generics for did not support it at the time i was dealing with that, for my use-cases. it was really annoying to deal with
@username7763
@username7763 19 дней назад
The exception handling comment got me thinking. Does anyone know a good reference for how the internals of .Net process exceptions? I'm used to the C++ / Windows world where they use SEH. The value of SEH is being able to have exceptions work properly even between calls written in different languages or compliers. But SEH is known for having a large-ish performance hit. I would think that the CLR doesn't need it for dotnet code. Plus SEH is Windows only. How does dotnet since .net core handle exceptions?
@jimread2354
@jimread2354 19 дней назад
It's not a List, but the built in System.Data.DataRow is an object[], as are the parameters for a command line application.
@luciannaie
@luciannaie 19 дней назад
where did you get these from? I want to see that LinkedIn post :)
@martinprohn2433
@martinprohn2433 19 дней назад
In your example of HttpClient and async await, the HrtpClient is but using await and therefore but preserving the stack, but that is also not necessary, because the calls are just cause the overloads with more parameters. So the stack would be smaller, but actually better because it would contain less noise.
@IElial
@IElial 19 дней назад
I'm using List/Dictionary for generic Deserialization (Json, xml, ...). Am I wrong to do so ?
@realsk1992
@realsk1992 19 дней назад
I think it is usually better to use "JsonElement" instead of Object, because that is what is really there (if using System.Text.Json), and it will gain more power to you. As for XML, it might be XmlNode, and so on.
@IElial
@IElial 19 дней назад
@@realsk1992 Actually it is the issue as I code an agnostic format's serializer so I cannot know in advance if it will be Json, XML, ... used by user.
@SeanLSmith
@SeanLSmith 19 дней назад
Have seen List once before, yet as you said, it was when the inbound data was unstructured/mangled. From there the code would try and cast it to a class type to see if there is any valid data and datatypes that the code cared about to continue logic checks later on. the code was not great and would not recommend.
@andraslacatos5832
@andraslacatos5832 19 дней назад
Hi Nick, are you planning to drop a promo code on the microservices deep dive course? Already have the getting started course and looking forward to get the deep dive as well
@dvdrelin
@dvdrelin 19 дней назад
about finally section... it protects on all exceptions thrown, even ThreadAbortException.. pretty useful, isn't it? what if TAE will be thrown before .Dispose() (or Close, whatever) invoking?
@user-ci4yb4zl5e
@user-ci4yb4zl5e 14 дней назад
Guys how can i see the source code in VS from .NET apis like Nick did with HttpClient. When i press F12 i see only signature i don't see any code inside.
@QwDragon
@QwDragon 17 дней назад
1. This advice could've been for VB_NET. There object can in some cases behave as C#'s dynamic. That means that list of object is kind of list of dynamic. Anyway, adwice to use correct type seems right. But there is another mistake there: string is not a value type, so it can't be example for boxing/unboxing. 2. Agree, no reason to use for instead of foreach almost always. Alco not all collections do have known length. 4. I think "excessive use" does mean that you have excaption in normal flow of work. For that case I completely agree with advice to avoid exceptions in normal flow and use them only for exceptional situations. 6. Seems controversial, but the reasoning is actually strange. 7. Close and dispose is the same thing in most cases. File streams are explicetely implementing IDisposable with Close method on own class and Dispose on interface. The point of adwice is in implicit handling by using statement instead of explicit close/dispose call. And the advice is right because of try-catch in recommended way. Check stackoverflow questions/answers for calling close - you hardly ever will see try-catch aroud it. And there is no point in writing all this stuff when it can be autogenerated by using using.
@afroeuropean5195
@afroeuropean5195 16 дней назад
Regarding boxing around 1:20 All the integers stored in a List will still be stored on the heap, not on the stack Btw, not disagreeing with the argument that you should still use the explicit type to avoid boxing and type juggling at runtime
@QwDragon
@QwDragon 16 дней назад
Ints won't be boxed in List, but in List they will.
@afroeuropean5195
@afroeuropean5195 15 дней назад
@@QwDragon correct, I was just replying to the statement about value types usually being stored on the stack. That is not the case when the value type is a member of a reference type
@blackenedsprite8542
@blackenedsprite8542 День назад
Further to above, the defining characteristic of value types is not where they are stored, it's that their type and value are stored together.
@davestorm6718
@davestorm6718 9 дней назад
try - catch, definitely. I write tons of I/O stuff and exceptions don't always happen when you think they will. For example, you can test a file to see if it has locks (or whatever), then believe that everything will be okay when you start reading it (big file), half-way in the read, a network card crashes (or drive hiccups, or what-have-you), then your IF check is worthless, and your program crashes because you didn't use exception handling. Believe me, stability is FAR more important than SPEED. A slow program is a nuisance, but a crashing program can be a career changer!
@mattyward1979
@mattyward1979 7 дней назад
The system I primarily interact with is all over the place with exception handling.. Loads of calls throw unhandled exceptions, sometimes return a packaged response with exceptions on an aggregated basis or a row by row basis. To have a catch all we also use an ExceptionFilter that has broad (but not exhaustive) knowledge of system expected exceptions with a fallback error extraction to a known exception type understood by the calling agent (UI) We can then just allow our server to throw shit willy nilly and it will always be processed correctly Probably an anti pattern in there somewhere, but saves me a lot of time :)
@David-id6jw
@David-id6jw 19 дней назад
@7:00 - One thing I'm seeing a good case for in eliminating this "control flow" use of exceptions is in object creation. In particular, a more functional approach helps reduce this. Many class types throw exceptions when doing data validation in the constructor (eg: ArgumentNullException.ThrowIfNull(myParameter)). The problem is that there is no other way to indicate failure when you're doing the validation in the constructor, so you _have_ to handle it via exception. A more "functional" approach (according to some) is to remove the data validation from the type itself, and only ever create the object through a Create() function (generally through a static class which specifies exactly what expectations it has about the types of objects it creates when using the result object type). The Create() function does the validation, and can return a null if validation failed, rather than throw an exception. The type itself can never throw because it never does any validation in the constructor. This then makes the idea of switching to an if/else block instead of a try/catch block make more sense, at least when you're creating objects.
@username7763
@username7763 19 дней назад
I think it depends on the purpose of the class. If the class is really an abstract data type that has to preserve the consistency and integrity of the data within it, it should really throw in the constructor. e.g. it shouldn't be possible to construct an array type of length -1. This significantly helps reasoning about code using it not having to worry about if the state is valid. There can be good cases for a factory method, but generally when you might have different kinds of factories or different creation logic. I hate having a Create function just in place of a constructor, it is unexpected compared to everything else.
@David-id6jw
@David-id6jw 19 дней назад
@@username7763 Oh, certainly. And at the most fundamental levels those kinds of protections are necessary. I think it's a matter of "validation" vs "not even representable". A null value for an array, or a length of 0, may not pass validation, but it's representable. An array with a length of -1 isn't even representable. I'm trying to adapt to a more "functional" style (basically, seeing how well a certain set of recommendations works vs how I normally write code), and the assertion is that the type is just a type, and shouldn't validate itself. The validation is moved to a separate class's factory methods. Though I think it works better from the grounds of using records as data types, rather than full classes. Behavior is lifted out of the type, rather than encapsulated by it as in standard OO. In that manner, you have the 'factory' class and say, "I'm going to use this type in this manner. Please make one for me." And if it's not able to (it fails validation), it returns null, and you don't have to deal with exceptions, just 'if' checks. And nullability warnings in the tooling make it easier to spot where you failed to make sure you got a valid object. If you didn't catch an exception, that could end up being handled anywhere. It's not an error to not catch the exception (at least until the program crashes). That also allows you to create a second factory class that generates the type using different validation considerations, and you don't have to figure out how to make both configurations work within the constructor of the type itself. (Just like an int is just an int, and doesn't care if you're using it to represent an Age value that can't be negative.) I've also found that it's much easier to reason about object creation when the Create() function can be named in a way that explains why it's being used. Compare with having multiple constructors with varying parameters, expectations, and validations; a "new MyObject(~params)" doesn't give you a clue about any such differences, but a Create() vs CreateWithNameOnly() can be a useful distinction.
@username7763
@username7763 19 дней назад
@@David-id6jw Wow that was a lot to write in the comments section! I think I followed it though. Yeah what you describe makes sense from a function programming style.
@arielspalter7425
@arielspalter7425 19 дней назад
The last one, using “using”, is actually a good advice. I didn’t understand why you concluded it as a bad advice.
@firestrm7
@firestrm7 18 дней назад
A good example for why critical thinking is a must-have skill. Nick usually resonates with me but this one seems not thoughtful. IDisposable is about releasing unmanaged resources and in that one you must trust the component and call Dispose - preferably using using :) - asap.
@anderskallin6107
@anderskallin6107 17 дней назад
I don't think it was the using statment he thought was wrong, but how the "mistake" called the Close-method, which is not the same as calling the Dispose-method.
@Sebastian----
@Sebastian---- 19 дней назад
Question: [12:52] Why is there the try-finally-block in the IL-Viewer?
@arjix8738
@arjix8738 19 дней назад
because the using statement is not part of the dotnet runtime, it is just syntactic sugar It is translated to a try/finally so the runtime can execute it
@AlmightyFuzz1
@AlmightyFuzz1 19 дней назад
Look into the concept of Lowering in C#, Nick has a great video on this. In a nutshell the C# code you write (the using statement and many other things) gets "compiled" into low level and usually optimised C# code that gets run by the runtime.
@ErazerPT
@ErazerPT 19 дней назад
@@arjix8738 Yes but not just. Same as lock() and (somevar as sometype), using is syntactic sugar. Just a sign that WAY too many people didn't do things properly so they shortcut'ed it and now people don't know the difference between .Close and .Dispose. And most don't even know what a destructor is, god bless them for working in 100% managed land... The "not just" part is "whatever happens inside using .Dispose MUST be invoked, as that is the sole purpose of using. And that's what finally{} does, call .Dispose whatever happens.
@ErazerPT
@ErazerPT 19 дней назад
Not sure about the question, if it's about the code lowering or the functional part, but assuming the second, when you use using, the one guarantee you have is that WHATEVER happens, .Dispose is called. So logically try{something}finally{whatever happened call .Dispose}.
@weicco
@weicco 18 дней назад
About try-catch. It would be good to mention you need to only catch only those exception you are expecting, not all of them. Because exceptions are for cases which can be foreseen like user pulling ethernet cable out of the wall in the middle of file transfer. I've seen people doing heck size of try-catches to catch _programming errors_ probably because they don't want to show the end user how bad they are at writing codes and _tests_.
@deadblazer8931
@deadblazer8931 18 дней назад
I've had never use List aside of list of unknown type before.
@georgeyoung2684
@georgeyoung2684 19 дней назад
“David Fowler who is basically… God” love it
@Zullfix
@Zullfix 19 дней назад
I used an ArrayList instead of a List once. It was my 3rd project in C# and I didn't know any better.
@zbaktube
@zbaktube 19 дней назад
Hi! Kind of did it: List objects = ... 😀
@nicholaspreston9586
@nicholaspreston9586 8 дней назад
Thanks for pointing out that LinkedIn is a bad place for .NET tips. I see a bunch of Indian devs putting out a bunch of syntactical patterns that either don't have an effect on anything or a just straight-up anti patterns. Very few developers, namely Sr. developers, put anything worthwhile out (like ways to implement the vertical slice architecture), and even they can be wrong. It's good to see someone set the record straight, because frankly, I sometimes get peeved at the amount of stupidity in some of the C# I read online. C# is not complicated, but so many devs overcomplicate it thanks to the cancer that is Object Oriented Programming.
@martinprohn2433
@martinprohn2433 19 дней назад
I thought ArrayList is just still there because of downward compatibility and should not be used anymore. (I actually used it once in WPF, because it is easy to create in XAML; but that was already over 10 years ago).
@BrankoDimitrijevic021
@BrankoDimitrijevic021 11 дней назад
Not sure why the last advice is “bad”. Quote from the docs: “If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent.“ So, disposing a connection is a perfectly legal way of closing it, so why wouldn’t you wrap it in `using` for exception safety?
@MrDuk-rk4ne
@MrDuk-rk4ne 17 дней назад
I’ve been a dotnet dev for 12 years and I’ve never ran across a List outside of very specific cases
@killerwife
@killerwife 15 дней назад
List of objects - json parsing - when I need to do some weird shenanigans with inconsistent content
@DxCKnew
@DxCKnew 19 дней назад
If you choose to utilize async/await in your code, it should be for all waiting or IO-based calls across the board, including in all the libraries you use. Otherwise you risk running into thread exhaustion even for one synchronous wait call, since each call like this will block an entire thread-pool thread until it finishes. In this context, it's very bad that Microsoft did not implement awaitable Directory.CreateDirectoryAsync() or File.DeleteAsync(). For the same reason, don't ever call a synchronous wait or IO-based calls on a thread-pool thread. If there is no way around it, use a non thread-pool thread for blocking calls like this.
@michi1106
@michi1106 19 дней назад
ArrayList was introduce with .net 2.0, before that there was no List-Type, only Arrays. So ArrayList was a big improvement for my project this time. But also, the object-type was bad, because i was forced to do a typecheck on every access on the List. So the later generic List was my dream.
@maschyt
@maschyt 18 дней назад
According to the ArrayList documentation it was introduced with .NET Framework 1.1.
@michi1106
@michi1106 18 дней назад
@@maschyt first comment was based on my memory, you are right, but at this time, i was just starting with C# in selflearning, so it still was an improvment for me :-)
@hexcrown2416
@hexcrown2416 18 дней назад
Json parser in a project i work on parses everything into obj where obj can be primitive or List or Dict i dont love it, but it works...
@user-dg5qy3cq8m
@user-dg5qy3cq8m 18 дней назад
The problems I see Time to time: ° Not using a factory and opening tons of connections. ° writing bad queries, loading all references when not needed ° writing interfaces above class declaration and not to separate files ° using semaphore in the wrong way without releasing it ° wrapping tasks into tasks with lamda Syntax.
@owenneilb
@owenneilb 19 дней назад
This first piece of advice is probably targeted at newer programmers who aren't familiar with how to properly structure code. I see lots of posts on reddit from new programmers trying to struggle through homework and fighting the language end up doing things like use List because they don't figure out they need an interface or something. Not the greatest advice though, as the solution is usually add an interface or common base class, rather than "use List", which doesn't help solve the problem.
@mehdizeynalov1062
@mehdizeynalov1062 16 дней назад
I think the reason they included List that wanted to sum the count to 10 as per heading. nonsense - didn't need to spend this much time on that issue.
@marvinjno-baptiste726
@marvinjno-baptiste726 16 дней назад
I have used a List before, but had a specific reason for it, which probably could have been mitigated by using an Interface (but hey, it was years ago and I was new to that!) - but List?? Why :-/
@johnjschultz5414
@johnjschultz5414 19 дней назад
I only use a collection of objects (List, Dictionary, etc) if the object is used by a lock statement. It's a rare case when I need it.
@xybersurfer
@xybersurfer 19 дней назад
2:10 i haven't seen people use List object for everything, but i have seen people unnecessarily use strings like Dictionary, when Dictionary would have worked
@pcdizzle13
@pcdizzle13 19 дней назад
A real async problem you’ll almost certainly run into, especially in distributed systems using http client is not thread exhaustion but socket exhaustion. Using statements are actually bad on http client. Make sure to re-use your http clients, the easiest way to do so is http client factory, or something super simple like a static http client that gets re-used .
@Ch17638
@Ch17638 19 дней назад
TF uses a list of object ? By the second item to me it is clear someone typed into chat GPT "generate 10 tips to increase performance on C#" and copied pasted it straight into linked-in.
@David-id6jw
@David-id6jw 19 дней назад
I was updating some old, old code recently, and found it was still using ArrayLists for things that could be moved to generics. Was a bit embarrassing, even if I know I wrote that in the .NET 1.1 days.
19 дней назад
On async/await vs returning the task, there are at least two big things to consider... I can only see one addressed here, the difference in stacktrace. The other one is throw vs rethrow of exceptions.
@MaximilienNoal
@MaximilienNoal 19 дней назад
I put async await everywhere even when I could just return a Task. Come at me! 😁
@isnotnull
@isnotnull 19 дней назад
HttpClient is a good example why you might avoid to do so. If you just run overloaded method from inside, you don't care about awiting it, because the overloaded method itself has logic in it which you are interested in
@rafazieba9982
@rafazieba9982 19 дней назад
@@isnotnull ... but if you want a rule of thumb putting async/await always without thinking about it is a good one
@discbrakefan
@discbrakefan 19 дней назад
Is there even a downside to this?
@billy65bob
@billy65bob 18 дней назад
@@discbrakefan If you return the Task, that method doesn't get added to the Task's stack. So it's marginally cheaper to execute, but it also makes it marginally harder to debug because the stack trace won't show how the Call Site got to the Executing Method. As such I would generally recommend only using this in one very specific niche scenario: Forwarding a method without a CancellationToken to one that does, and only when the `default` keyword isn't applicable. e.g. Task MyMethod(params int array[]) => MyMethod(CancellationToken.None, array) async Task MyMethod(CancellationToken token, params int array[]) {...}
@isnotnull
@isnotnull 18 дней назад
@@rafazieba9982 As a rule I assign a result of await to a variable and return the variable instead of expression. Helps in debugging at no performance cost
@davestorm6718
@davestorm6718 9 дней назад
The only time I had to use list of objects was for integrating with a crappy api (for a specific accounting program).
@winchester2581
@winchester2581 11 дней назад
ArrayList really gives me those flashbacks from Java
@saberint
@saberint 19 дней назад
Hmm we use a dictionary because the value could be almost anything (int, float, string, datetime etc)
@fusedqyou
@fusedqyou 19 дней назад
`List` is completely pointless considering most collection types have a non-generic variants that does exactly this.
@jimmyzimms
@jimmyzimms 19 дней назад
"The term exception is the frequency of a situation, though it should be rare, but in taking exception in how they were used in this condition" -Jeffrey Richter
@filiecs3
@filiecs3 19 дней назад
I actually have seen people use List when they don't need to. Typically JavaScript programmers trying to learn C#.
@Kegwen
@Kegwen 18 дней назад
I don't know that I've ever wanted or needed the object "type" in my entire life
@MasoudKazemiBidhandi
@MasoudKazemiBidhandi 17 дней назад
It is sad to see some people start to give advice to others and cant give out the example for it. for the Exception part, in some source code you see that there are cases that coder throw Exception in his/her code just to break the execution and return immediately back to caller. this kind of coding is not desirable and should be avoided if possible. so its not even about placing Try, Catch, Finally in codes which is perfectly fine.
@mikeblair4545
@mikeblair4545 19 дней назад
Personally the best advice i can give is to stop typing out stringbuilder and just type out string. By not making your progam compile builder you save 7 characters, making your application smaller.
@berkanbilgin1472
@berkanbilgin1472 19 дней назад
Too bold statements, as always. What a click bait..
@MarvinKleinMusic
@MarvinKleinMusic 19 дней назад
I'm using a List of objects to store different type of classes within a memory cache so I don't need to call a database for everything which rarely changes
@Biker322
@Biker322 19 дней назад
Can you not use generics for that, ie. List ? I do something similar for caching. But using generics , then you can also restrict the list to be classes inherited from your Entity base object.
@MarvinKleinMusic
@MarvinKleinMusic 19 дней назад
@@Biker322 there is no entity base model. Just 10 different classes which are all stored in one list.
@DmitryBaranovskiyMrBaranovskyi
@DmitryBaranovskiyMrBaranovskyi 19 дней назад
List - never. For 15 years.
@milendenev4935
@milendenev4935 19 дней назад
same but for 10
@johnnyblue4799
@johnnyblue4799 19 дней назад
I'll do it once, to see how my colleagues will react! :)))
@DmitryBaranovskiyMrBaranovskyi
@DmitryBaranovskiyMrBaranovskyi 19 дней назад
XD))
@milendenev4935
@milendenev4935 19 дней назад
@@johnnyblue4799 might die, just saying
@johnnyblue4799
@johnnyblue4799 19 дней назад
@@milendenev4935
@tvardero
@tvardero 19 дней назад
List of objects might be used when theres not base class in items you want to hold, but they are still have common usages. In my case this is for COM library for some WinForm application, they have custom components that do not have base class (so they are stored in object collection). Second situation could be when I'm dealing with open generic interfaces, that also do not have base interface. Or when in some rare case non-generic interface implements generic one with type object. Happens.
@veec1539
@veec1539 19 дней назад
Just got assigned a side project with a few devs. No c# experience, their code is littered with var, dynamic, and object.... Unfortunately they wore something a VP wanted so my hands are tied....
@TheDiggidee
@TheDiggidee 19 дней назад
Currently stuck in the async/await argument with someone. It's not fun
@xlerb2286
@xlerb2286 4 дня назад
The only time I've seen a List used was someone had set up a list of objects to use as sync roots, one per unique thread id. Yes, I know, that's all kinds of bad. That was a fun little job unsnarling that code. As for the whole IDisposable mess Eric Lippert said IDisposable was the 2nd worst mistake in C#. I think he's underrated it ;)
@ProSunnySharma
@ProSunnySharma 18 дней назад
I find the title misleading. It's like stop eating to cure your body!! Later the vide says - use async/await judiciously!
@berkanbilgin2287
@berkanbilgin2287 17 дней назад
Thats typical with his video thumbnails and contents. Classic click bait he keeps doing. This guy becoming annoying to me recently
@ernstgreiner5927
@ernstgreiner5927 19 дней назад
These Code Cop videos are really horror. I recommend „Nightmare on Elm Street“ or something else as starter to get used to it…
@DanielAWhite27
@DanielAWhite27 19 дней назад
Close often delegates to Dispose
@jackkendall6420
@jackkendall6420 19 дней назад
I'm glad someone else recognises David Fowler as God
@alexby2600
@alexby2600 19 дней назад
I don't know how to overcome it, more and more advice that appears is worse than the previous ones
@sheeeeep12345
@sheeeeep12345 19 дней назад
I used a list of objects recently when using newtonsoft to deserialize a stirng into an list of an DTO (attributerecord) where a single attributerecord can have an property that could have a dynamic type like string, int, entityreference (class) or list of objects.
@igiona
@igiona 19 дней назад
This one was really a stretch....and as many stated, using() should be preferred over calling Dispose. Maybe you fancy a CodeCop video of your selfs? 😂
@billy65bob
@billy65bob 18 дней назад
I think his point was more that using calls Dispose(), instead of Close().
@igiona
@igiona 18 дней назад
​​​@@billy65bobyeah, but he gets very aggressive because he (intentionally?) misunderstood the advice. Imho the original point was to use using() instead of calling Dispose()... But yeah, if you want to see dirt there ..you definitely can ;) The stretch is that in order to blame the advice, he mentions that "yeah using is there, but who cares...you can call try finally and Dispose yourself" and this is a bad advice imho)
@yv989c
@yv989c 19 дней назад
Saw the title and just came here to say LOL. (I haven't watch the video, yet)
@asedtf
@asedtf 19 дней назад
I used a list of objects because it legitimately had to store any value in it to be consumed by something else that would perform some kind of logic on the value. It was the easiest way at the time, performance wasn't important and re-architecting the code would take weeks Working with enterprise software legacy code sure does pay the bills and I'm not paid by the line of code
@lordmetzgermeister
@lordmetzgermeister 19 дней назад
I would've made a class with a property inside and instead of list.Add(value) it would be list.Add(new() { Prop = value }), which is mildly less headache-inducing and easier to modify/expand in the future.
@asedtf
@asedtf 19 дней назад
@@lordmetzgermeister oh and what would be the type of that Prop? Might it be object?
@okmarshall
@okmarshall 19 дней назад
@@asedtf Yes, but the benefit is you can add other properties to that class that contain other information.
@asedtf
@asedtf 19 дней назад
@@okmarshall okay, sure, but that's beyond the scope of the original suggestion. The problem didn't need it
@drugged_monkey
@drugged_monkey 19 дней назад
I'm in C# nearly 12 years and I never seen List even in worst possible pieces of code. Yes, I meet object[] sometimes but mostly in code related to really dark ages of .Net Framework 1.1/2
@blackenedsprite8542
@blackenedsprite8542 День назад
Is the title a 'killing your gains' parody? I hope so...
@jslocomb
@jslocomb 16 дней назад
Who is using List 🤣
@nikize
@nikize 3 дня назад
Prove that dropping async/await destroys stack trace in netcore. It doesn't! Follow suggestions of asyncfixer analyser!
Далее
Here's why Chrome is SLOW (It's NOT your RAM)
10:24
Просмотров 1,3 млн
New Gadgets! Bycycle 4.0 🚲 #shorts
00:14
Просмотров 4,6 млн
Sprinting with More and More Money
00:29
Просмотров 32 млн
5 New AI Tools You Should Try
9:18
Просмотров 8 тыс.
Create a React App: What you should know
5:44
You Are WRONG About 0 Based Indexing
25:02
Просмотров 204 тыс.
MS-DOS has been Open-Sourced!  We Build and Run it!
15:01
FANG Interview Question | Process vs Thread
3:51
Просмотров 273 тыс.
The New .NET 9 HybridCache That You Must Upgrade To!
14:34