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

Sdílet
Vložit
  • čas přidán 12. 05. 2024
  • 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

Komentáře • 210

  • @antonmartyniuk
    @antonmartyniuk Před 10 dny +322

    Stop using your PCs, save the electricity

    • @futurexjam2
      @futurexjam2 Před 10 dny +1

      :)) I will loose also my private jet :)

    • @testitestmann8819
      @testitestmann8819 Před 10 dny +25

      Avoid bugs - stop writing code

    • @DemoBytom
      @DemoBytom Před 10 dny +10

      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 Před 10 dny +2

      stop using electricity, use solar energy

    • @discbrakefan
      @discbrakefan Před 9 dny

      Yeah get a Mac 😂

  • @klocugh12
    @klocugh12 Před 10 dny +90

    "Don't leave your house, you might get hit by a car"

    • @POWEEEEEER
      @POWEEEEEER Před 7 dny +1

      "Don't stay in house, the ceiling might collapse on you"

  • @maacpiash
    @maacpiash Před 9 dny +14

    11:08 "...David Fowler, who's basically, God..."
    Truer words have never been said 🙌🏽

  • @tymurgubayev4840
    @tymurgubayev4840 Před 10 dny +35

    normal brain: List
    galaxy brain: List
    (old brain: ArrayList)

  • @EikeSchwass
    @EikeSchwass Před 10 dny +46

    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 Před 10 dny +2

      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 Před 10 dny

      I thought only sqlite has this problem

    • @JacobNax
      @JacobNax Před 10 dny +3

      That also happened to us with StackExchange Redis due to a bug x)

    • @eddypartey1075
      @eddypartey1075 Před 10 dny +1

      ​@@JacobNax how do u face this issue with StackExchange Redis? I'm curious

    • @Rick104547
      @Rick104547 Před 10 dny

      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.

  • @NickMaovich
    @NickMaovich Před 10 dny +34

    "Seed with random number" while there is 420 will never not crack me up :D

  • @Chainerlt
    @Chainerlt Před 10 dny +15

    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 Před 10 dny +3

      "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 Před 10 dny +9

      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 Před 10 dny

      @@mk72v2oq There has to be an analyzer that does that already.

    • @billy65bob
      @billy65bob Před 9 dny +4

      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 Před 9 dny

      @@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.

  • @ChristopherJohnsonIsAwesome

    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.

  • @billy65bob
    @billy65bob Před 9 dny +2

    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.

  • @Drachencheat
    @Drachencheat Před 10 dny +20

    When the advice is so outrageous that your pullover transforms into a t-shirt

    • @parlor3115
      @parlor3115 Před 10 dny +1

      That's actually welcome since it's getting really warm in here

    • @maacpiash
      @maacpiash Před 9 dny +1

      Watching the video from Australia, I appreciate his t-shirt being transformed back into the pullover.

  • @DevLeader
    @DevLeader Před 10 dny +6

    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 Před 3 dny

      Spot on, shows the poster doesn't code, so it's junk, there's gonna be more of these junky articles.

  • @pali1980
    @pali1980 Před 10 dny +2

    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

  • @Ivolution091
    @Ivolution091 Před 10 dny +3

    Thanks for referencing to David Fowler's AsyncGuidance article!

  • @bslushynskyi
    @bslushynskyi Před 9 dny

    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.

  • @ErazerPT
    @ErazerPT Před 10 dny +5

    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 Před 10 dny +4

      You don’t use ArrayList because it is not generic, plain and simple.

  • @davestorm6718
    @davestorm6718 Před 2 hodinami

    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!

  • @davidmartensson273
    @davidmartensson273 Před 9 dny

    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.

  • @dgtemp
    @dgtemp Před 9 dny

    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

  • @CharlesBurnsPrime
    @CharlesBurnsPrime Před 9 dny

    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.

  • @ryan-heath
    @ryan-heath Před 10 dny +2

    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.

  • @username7763
    @username7763 Před 10 dny

    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.

  • @David-id6jw
    @David-id6jw Před 10 dny

    @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.

  • @makescode
    @makescode Před 10 dny +2

    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.

  • @bankashvids
    @bankashvids Před 9 dny

    This was a good one. Thanks!

  • @itsallgravy_9437
    @itsallgravy_9437 Před 10 dny +1

    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...

  • @alexandernava9275
    @alexandernava9275 Před 10 dny

    I have only seen List for not knowing type. Though I will say, I would lean generics if you don't know the type.

  • @martinprohn2433
    @martinprohn2433 Před 10 dny

    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.

  • @_tanoshi
    @_tanoshi Před 9 dny

    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

  • @jongeduard
    @jongeduard Před 9 dny +1

    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.

  • @ThomasJones77
    @ThomasJones77 Před 10 dny +11

    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 Před 10 dny +4

      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 Před 9 dny +2

      @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 Před 9 dny

      @@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 Před 9 dny

      @@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 Před 9 dny

      @@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.

  • @Nobonex
    @Nobonex Před 10 dny +3

    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 Před 10 dny +1

      Sounds like a JavaScript developer.

  • @jimread2354
    @jimread2354 Před 10 dny

    It's not a List, but the built in System.Data.DataRow is an object[], as are the parameters for a command line application.

  • @tlcub4bear
    @tlcub4bear Před 8 dny

    12:47 what magic did you use to show the code underneath?

  • @deadblazer8931
    @deadblazer8931 Před 9 dny

    I've had never use List aside of list of unknown type before.

  • @Zullfix
    @Zullfix Před 10 dny

    I used an ArrayList instead of a List once.
    It was my 3rd project in C# and I didn't know any better.

  • @luciannaie
    @luciannaie Před 10 dny

    where did you get these from? I want to see that LinkedIn post :)

  • @user-dg5qy3cq8m
    @user-dg5qy3cq8m Před 9 dny

    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.

  • @username7763
    @username7763 Před 10 dny +1

    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?

  • @andraslacatos5832
    @andraslacatos5832 Před 10 dny

    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

  • @AtikBayraktar
    @AtikBayraktar Před 9 dny

    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?

  • @David-id6jw
    @David-id6jw Před 10 dny

    @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 Před 10 dny +1

      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 Před 10 dny +1

      @@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 Před 10 dny

      @@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.

  • @SeanLSmith
    @SeanLSmith Před 10 dny

    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.

  • @zbaktube
    @zbaktube Před 10 dny

    Hi! Kind of did it: List objects = ... 😀

  • @afroeuropean5195
    @afroeuropean5195 Před 7 dny

    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 Před 7 dny

      Ints won't be boxed in List, but in List they will.

    • @afroeuropean5195
      @afroeuropean5195 Před 6 dny

      @@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

  • @dvdrelin
    @dvdrelin Před 10 dny

    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?

  • @johnjschultz5414
    @johnjschultz5414 Před 10 dny

    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.

  • @DxCKnew
    @DxCKnew Před 10 dny

    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.

  • @QwDragon
    @QwDragon Před 8 dny

    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.

  • @hexcrown2416
    @hexcrown2416 Před 9 dny

    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...

  • @michi1106
    @michi1106 Před 10 dny

    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 Před 9 dny

      According to the ArrayList documentation it was introduced with .NET Framework 1.1.

    • @michi1106
      @michi1106 Před 9 dny

      @@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 :-)

  • @arielspalter7425
    @arielspalter7425 Před 9 dny +1

    The last one, using “using”, is actually a good advice. I didn’t understand why you concluded it as a bad advice.

    • @firestrm7
      @firestrm7 Před 9 dny

      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 Před 8 dny

      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.

  • @mikeblair4545
    @mikeblair4545 Před 9 dny

    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.

  • @user-ci4yb4zl5e
    @user-ci4yb4zl5e Před 5 dny

    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.

  • @weicco
    @weicco Před 9 dny

    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_.

  • @Sebastian----
    @Sebastian---- Před 10 dny

    Question: [12:52] Why is there the try-finally-block in the IL-Viewer?

    • @arjix8738
      @arjix8738 Před 10 dny +1

      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 Před 10 dny

      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 Před 10 dny

      @@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 Před 10 dny

      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}.

  • @MrDuk-rk4ne
    @MrDuk-rk4ne Před 7 dny

    I’ve been a dotnet dev for 12 years and I’ve never ran across a List outside of very specific cases

  • @georgeyoung2684
    @georgeyoung2684 Před 10 dny +10

    “David Fowler who is basically… God” love it

  • @BrankoDimitrijevic021

    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?

  • @owenneilb
    @owenneilb Před 10 dny

    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.

  •  Před 10 dny

    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.

  • @David-id6jw
    @David-id6jw Před 10 dny

    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.

  • @IElial
    @IElial Před 10 dny

    I'm using List/Dictionary for generic Deserialization (Json, xml, ...). Am I wrong to do so ?

    • @realsk1992
      @realsk1992 Před 9 dny

      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 Před 9 dny

      @@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.

  • @Ch17638
    @Ch17638 Před 10 dny

    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.

  • @xybersurfer
    @xybersurfer Před 10 dny

    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

  • @mehdizeynalov1062
    @mehdizeynalov1062 Před 7 dny

    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.

  • @Kegwen
    @Kegwen Před 9 dny

    I don't know that I've ever wanted or needed the object "type" in my entire life

  • @martinprohn2433
    @martinprohn2433 Před 10 dny

    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).

  • @jimmyzimms
    @jimmyzimms Před 9 dny

    "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

  • @davestorm6718
    @davestorm6718 Před 3 hodinami

    The only time I had to use list of objects was for integrating with a crappy api (for a specific accounting program).

  • @saberint
    @saberint Před 10 dny

    Hmm we use a dictionary because the value could be almost anything (int, float, string, datetime etc)

  • @killerwife
    @killerwife Před 6 dny

    List of objects - json parsing - when I need to do some weird shenanigans with inconsistent content

  • @marvinjno-baptiste726

    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 :-/

  • @pcdizzle13
    @pcdizzle13 Před 10 dny +3

    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 .

  • @fusedqyou
    @fusedqyou Před 10 dny

    `List` is completely pointless considering most collection types have a non-generic variants that does exactly this.

  • @winchester2581
    @winchester2581 Před 2 dny

    ArrayList really gives me those flashbacks from Java

  • @tvardero
    @tvardero Před 10 dny +2

    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.

  • @MarvinKleinMusic
    @MarvinKleinMusic Před 10 dny +1

    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 Před 10 dny

      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 Před 9 dny

      @@Biker322 there is no entity base model. Just 10 different classes which are all stored in one list.

  • @DmitryBaranovskiyMrBaranovskyi

    List - never. For 15 years.

  • @filiecs3
    @filiecs3 Před 10 dny

    I actually have seen people use List when they don't need to. Typically JavaScript programmers trying to learn C#.

  • @MasoudKazemiBidhandi
    @MasoudKazemiBidhandi Před 8 dny

    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.

  • @MaximilienNoal
    @MaximilienNoal Před 10 dny +12

    I put async await everywhere even when I could just return a Task. Come at me! 😁

    • @isnotnull
      @isnotnull Před 10 dny +1

      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 Před 10 dny +3

      @@isnotnull ... but if you want a rule of thumb putting async/await always without thinking about it is a good one

    • @discbrakefan
      @discbrakefan Před 9 dny

      Is there even a downside to this?

    • @billy65bob
      @billy65bob Před 9 dny

      @@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 Před 9 dny

      @@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

  • @DanielAWhite27
    @DanielAWhite27 Před 10 dny

    Close often delegates to Dispose

  • @TheDiggidee
    @TheDiggidee Před 10 dny

    Currently stuck in the async/await argument with someone. It's not fun

  • @veec1539
    @veec1539 Před 10 dny

    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....

  • @sheeeeep12345
    @sheeeeep12345 Před 10 dny

    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.

  • @drugged_monkey
    @drugged_monkey Před 10 dny +1

    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

  • @asedtf
    @asedtf Před 10 dny +3

    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 Před 10 dny

      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 Před 10 dny

      @@lordmetzgermeister oh and what would be the type of that Prop? Might it be object?

    • @okmarshall
      @okmarshall Před 10 dny

      @@asedtf Yes, but the benefit is you can add other properties to that class that contain other information.

    • @asedtf
      @asedtf Před 10 dny

      @@okmarshall okay, sure, but that's beyond the scope of the original suggestion. The problem didn't need it

  • @ernstgreiner5927
    @ernstgreiner5927 Před 10 dny

    These Code Cop videos are really horror. I recommend „Nightmare on Elm Street“ or something else as starter to get used to it…

  • @jackkendall6420
    @jackkendall6420 Před 10 dny

    I'm glad someone else recognises David Fowler as God

  • @ProSunnySharma
    @ProSunnySharma Před 9 dny +1

    I find the title misleading. It's like stop eating to cure your body!! Later the vide says - use async/await judiciously!

    • @berkanbilgin2287
      @berkanbilgin2287 Před 8 dny +2

      Thats typical with his video thumbnails and contents. Classic click bait he keeps doing. This guy becoming annoying to me recently

  • @igiona
    @igiona Před 10 dny

    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 Před 9 dny

      I think his point was more that using calls Dispose(), instead of Close().

    • @igiona
      @igiona Před 9 dny

      ​​​@@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)

  • @isnotnull
    @isnotnull Před 10 dny +1

    connection.Close() and connection.Dispose() are not equal
    Disposed connection can actually still be opened, go to the pool and reused by EF Core again. Closed connection is closed indeed and cannot be reused by EF Core pool.

  • @yv989c
    @yv989c Před 10 dny

    Saw the title and just came here to say LOL. (I haven't watch the video, yet)

  • @alexby2600
    @alexby2600 Před 10 dny +1

    I don't know how to overcome it, more and more advice that appears is worse than the previous ones

  • @iambonmucho
    @iambonmucho Před 10 dny

    Sometimes I use List for really small projects where performance isn't an issue and too much abstraction takes too much time.

  • @lizard450
    @lizard450 Před 10 dny

    Remember when using ArrayList was just fine? I member

    • @user-dh6jq5gs7g
      @user-dh6jq5gs7g Před 10 dny

      Apparently, MSDN recommends using List instead of ArrayList for heterogeneous lists.

  • @jslocomb
    @jslocomb Před 7 dny

    Who is using List 🤣

  • @jfftck
    @jfftck Před 10 dny

    I like how it is bad advice to do List, but that is what JavaScript arrays are and it is ranked higher than C#. So, using them in C# should still be faster than all JavaScript arrays, but it is always preferable to use an exact type in all instances for multiple reasons: type safety, performance, memory usage, etc…

  • @alexdarby9392
    @alexdarby9392 Před dnem

    Async await does not even use threads, at least not in the way people think

  • @user-tk2jy8xr8b
    @user-tk2jy8xr8b Před 10 dny

    We still have List in the code written by other teams. They did it to "support polymorphism".

    • @magimix2000
      @magimix2000 Před 10 dny

      Like how the monster from "The Thing" exhibits polymorphism, presumably 😅

    • @activex7327
      @activex7327 Před 7 dny

      That's not polymorphism, ... That's a misuse/abuse of the concept.
      I bet your team also uses inheritance for re-use.

    • @user-tk2jy8xr8b
      @user-tk2jy8xr8b Před 7 dny

      @@activex7327 well technically it is subtype polymorphism. My team doesn't. How much did you bet?

    • @activex7327
      @activex7327 Před 7 dny

      @@user-tk2jy8xr8b You completely missed my point, I know what it is, it is just no used correctly. Assigning anything to an object for polymorphic reason is just abuse. Assigning anything to an object is like passing void pointers in C++. It is not for polymorphism.
      Your team is doing things wrong, and if I would do code reviews I would probably find other problems.

    • @user-tk2jy8xr8b
      @user-tk2jy8xr8b Před 7 dny

      @@activex7327 you completely missed my point, my team is not using `object`. I clean that crap out.