How IDisposable and Using Statements Work Together in C#

Поділитися
Вставка
  • Опубліковано 4 лют 2024
  • IDisposable is a really powerful tool for ensuring proper resource management and safety for your application. In this video, we are going to look at how IDisposable and Using statements work together to protect your resources.
    Full Training Courses: IAmTimCorey.com
    Source Code: leadmagnets.app/?Resource=IDi...
    Mailing List: signup.iamtimcorey.com/

КОМЕНТАРІ • 136

  • @danielrubio3386
    @danielrubio3386 4 місяці тому +15

    Love these short and to the point videos.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +1

      Glad you like them!

    • @WyldStallion-bs9oo
      @WyldStallion-bs9oo 2 місяці тому

      @@IAmTimCorey So is USING a reason you can cite as a means to prevent database deadlocks?

  • @abo1428
    @abo1428 4 місяці тому +7

    Thank you so much Tim! I used Disposables here and there. But what I learned today is the order, when Dispose gets called. Great!

  • @randyriegel8553
    @randyriegel8553 4 місяці тому +8

    Good timing :) I'm working on a memory leak problem at the moment for a project I just got kind of thrown into. Funny story about memory and resources. A smaller/medium sized company I worked for had a dedicated SQL Server machine. After a day or 2 the SQL server would be around 80% memory usage but CPU was running very low percentage and performance was great. Me as a software engineer tried to explain to the DBA and the Hardware guy that SQL Server will use as much memory as it can by default for caching and things. Memory is there for a reason... to USE IT! But they bumped it up from 64GB ram to 128GB. Still 80-90 percent. I left there about 7 years ago... they probably are still rebooting that server everyday.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +5

      😂 Yep, time for them to read up on how SQL works. I'm not sure if you have ever looked into it, but how it reserves memory is fascinating. It actually works backwards, reserving from the end back towards the beginning of your memory. That way, it won't have to fight with the OS or other applications for the same memory addresses and it can have a more contiguous chunk of memory.

  • @BigyanChap
    @BigyanChap 4 місяці тому +1

    Wow. What a clarity! Never understood IDisposable in such a pristine way!!

  • @00oKMo00
    @00oKMo00 4 місяці тому

    Love it. Straight to the point and easy to digest. Thanks Tim.

  • @cyberbru1
    @cyberbru1 4 місяці тому

    Love this short videos Tim! Thank you for your content

  • @felixmelendez6255
    @felixmelendez6255 4 місяці тому

    Great explanation! First time I see it explained in comprehensive manner and in detail. 👍

  • @MZZenyl
    @MZZenyl 4 місяці тому +3

    Interesting note: ref structs can't implement interfaces, but if you define a "public void Dispose()" method in a ref struct, you'll be allowed to use it in a using statement, and the method will be called on scope exit as expected. This is a special case for ref structs, as classes and non-ref structs cannot simply duck type a Dispose method.

  • @krisztianlun3463
    @krisztianlun3463 4 місяці тому

    This video is a perfect fit for my Arduino project. Perfect timing! Thank you!

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      I’m glad it was helpful.

  • @microtech2448
    @microtech2448 4 місяці тому +3

    Beautifully explained

  • @user-ew4wv9qb1g
    @user-ew4wv9qb1g 4 місяці тому

    Thank you Tim. I am a beginner and I have used IDisposable and seen it used other code basebut never really understood it. This was insightful!

  • @millstj
    @millstj 4 місяці тому

    Wonderfully explained. Thanks Tim!

  • @christopherlebron6912
    @christopherlebron6912 4 місяці тому

    Great video! I was actually looking how to implement this today. Learned a lot, thanks.

  • @nandareddy4831
    @nandareddy4831 4 місяці тому

    Thanks Tim !, Very Good Explanation, Now I got better understanding of Dispose method. Great work !..

  • @BrentHollett
    @BrentHollett 4 місяці тому

    IDisposable and Using Blocks are also great when dealing with locks. By wrapping a lock in a class that returns disposable token when you call .Lock(), and then in the dispose of the token, calling the .Unlock, you can ensure that you always unlock your locks when you exit the using block. It makes it far easier to ensure you never forget.

  • @JahirulIslam-le6ux
    @JahirulIslam-le6ux 4 місяці тому

    Excellent tutorial and many many thanks

  • @MahmoudRKeshk
    @MahmoudRKeshk 13 днів тому

    Absolutely clear ! and directly to point.

  • @tinker7722
    @tinker7722 4 місяці тому

    Thank you very much! That's very nicely explained and demonstrated!😊❤

  • @nickysmusic4592
    @nickysmusic4592 4 місяці тому

    Awesome!!! I just ran into the problem. Thanks for the fix

  • @MarioStaats
    @MarioStaats 4 місяці тому

    Great information and brilliant explained. *thumbsUp

  • @thegirigat
    @thegirigat 4 місяці тому

    Very useful information, thank you

  • @AthanSousouris
    @AthanSousouris 4 місяці тому

    Great video!

  • @salvatoreamaddio2983
    @salvatoreamaddio2983 4 місяці тому

    Thank you!

  • @gopikrishnag41
    @gopikrishnag41 4 місяці тому

    Nice informative video, thx

  • @handypda
    @handypda 4 місяці тому

    Cheers Tim

  • @guilhermealves577
    @guilhermealves577 16 днів тому

    Perfect!!

  • @199772AVVI
    @199772AVVI 4 місяці тому +3

    Why not also show what hides behind the using statement and what is the Dispose pattern and why it was introduced and is good to use... Maybe a topic for a more in-depth video on IDisposable?

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +1

      What do you mean "what hides behind the using statement"? I showed you how it works. If you mean the code that Microsoft wrote to call the Dispose method, I'm not sure that is of real, practical value. You know what it does and why it does it. Knowing how might be interesting, but I'm not sure how it changes what you do on a day-to-day basis. Is there something that you think would be beneficial in that knowledge?

  • @jasonrichmeier32
    @jasonrichmeier32 4 місяці тому

    I am amazed / baffled at how many .NET developers don't know how / when to use the using statement in conjunction with the IDisposable interface / disposable pattern.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +1

      Well, hopefully more will know about it now.

  • @alexisgomez1198
    @alexisgomez1198 2 місяці тому

    Do Tim Corey has a video about using the lock keyword to lock a thread? Or when to lock a thread?

    • @IAmTimCorey
      @IAmTimCorey  2 місяці тому

      Not yet, but that would be a great suggestion! In order for me to track it and for others to be able to vote on it, please add it to suggestions.iamtimcorey.com

  • @Max_Jacoby
    @Max_Jacoby 4 місяці тому

    What would be really interesting is to how to work with objects in a field that are disposable. Should I make the whole class disposable and call Dispose on a field inside Dispose of a class?

  • @robertlaszlo6074
    @robertlaszlo6074 4 місяці тому

    Thank you! Very helpful. One question: if I use IDisposable, should I still close the connection as a function of DoWork()?

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      It depends on the library, but in general, no, it will be closed for you.

  • @georgestavrou8785
    @georgestavrou8785 4 місяці тому

    Excellent video. What will happen if the function inside was having a using statement??

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +2

      Using statements call the dispose method when they go out of scope. That means if you have nested ones, they will be going out of scope and closing properly.

  • @wagdyusrey7863
    @wagdyusrey7863 4 місяці тому

    Thanks for your help❤ but what is the difference between it and distructor

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      I think that would be a good topic for a video. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @Lehnargh
    @Lehnargh 3 місяці тому

    Would be cool if you could also talk about what you can think of if the whole server crashes, and a connection is not closed. A little bit more of a holistic view to tackle the problem not only what you can do in the code. Of course this should be not be in detail, but only as a further train of thought to teach us youngster to find better solutions to real problems of operating systems.

    • @IAmTimCorey
      @IAmTimCorey  2 місяці тому

      Thanks for the suggestion! In order for me to track it and for others to be able to vote on it, please add it to suggestions.iamtimcorey.com

  • @DavidMartin-vs1dm
    @DavidMartin-vs1dm 4 місяці тому

    Tim, did you implement this in the Suggestions website tutorial? I built my MongoDB access based on this tutorial but I don't remember the use of IDisposable. I may have just missed it. My Blazor pages have the @inject Interface name class. Does an interface by default implement IDisposable?

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +1

      Yep. If you have the code, you can look at the CreateSuggestion method among others to see how we use one. And no, an interface does not by default implement IDisposable. You have to do that per class.

  • @holger_p
    @holger_p 4 місяці тому

    That's really the bare minimum. Something about Finalizers (destructors) or the often seen pattern with SuppressFinalize, and Dispose(bool disposing) would have been nice.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +1

      That's outside the scope of covering IDisposable, but it is something that I could cover. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

    • @holger_p
      @holger_p 4 місяці тому

      @@IAmTimCorey Right, you covered existing classes with IDisposable, not the implementation of IDisposable.
      The title is a bit missleading, cause in 98% of cases, if you talk about interfaces, it's how and where to implement it.
      Here you start with "imagine you have a class implementing it .. we don't talk about the class".

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      How you implement it (what you do in Dispose) depends entirely on what unmanaged resources you have open or other tasks that you need to be performed at the end. I showed how that Dispose method gets called. What you do inside depends on your specific situation.

  • @deniskarpenko4808
    @deniskarpenko4808 4 місяці тому

    Good video, but also IDisposable pattern with GC would be good to see to a new in c#

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @abhigupta3193
    @abhigupta3193 4 місяці тому

    hello sir (how can use dispose with DI), could you please make one video for code memory optimizing and memory leaking one of my microservices taking too much memory in our AKS, the database I am using Azure Cosmos DB,
    please make a video on this important topic also I have to try to understand how to use a profiler to check and make a video on how to use a profiler also

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @AhmadElkhouly
    @AhmadElkhouly 4 місяці тому

    Thank you for this. I have a question, it may be irrelevant here but I hope you can help: I have a view (user control) and a presenter that the view is injected to. The view has no reference to the presenter and it just publishes events that the presenter subscribes to. The question is if I disposed the view, would the presenter be GC'd?
    Is there a way to test if the presenter gets collected? Should I worry about this? Thank you in advance.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      If the view is injected into the presenter and the view is disposed, the presenter could still be active. Maybe I'm not understanding your architecture.

  • @trustingod0
    @trustingod0 4 місяці тому

    Hey Mr. Corey. What’s the difference between using the using directive of a class and referencing a project. Just thought I would ask.

    • @holger_p
      @holger_p 4 місяці тому

      As you say it, it's two different things. You can also ask for the difference between Corona beer and Corona virus, that makes as much sense to ask.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +1

      I think I covered the using statement fairly well in this video. It calls the Dispose method when the call goes out of scope. The using directive (the entry at the top of the class file that says something like "using System.IO;") is just a shortcut. For example, We say "Console.WriteLine" a lot in Console apps, but the full name is "System.Console.WriteLine". By adding a using directive for System (which is now implicitly added to all new projects), we can shorten that call. It does not add any new libraries or increase the size of our project in any way.

  •  4 місяці тому +1

    now you put a doubt in my mind... when we use dependency injection on a controller, we never close connection. Does EF core close connections automatically?

    • @mohammedabujayyab6146
      @mohammedabujayyab6146 4 місяці тому +1

      good question 👍

    • @199772AVVI
      @199772AVVI 4 місяці тому +1

      I'm going to assume that you've registered EF Core as scoped (default for AddDbConnection or whatever it is)... The answer is yes, the Microsoft DI automatically calls the Dispose/DisposeAsync as soon as the scope is diposed, controllers are also used as scope. Every HTTP request is (usually) a new DI scope.

    • @simon-white
      @simon-white 4 місяці тому +1

      If you override the Dispose/DisposeAsync method, you can monitor this happening with logging/debugging. Just need to remember to also call the base.DisposeAsync etc.

  • @tiisetsontsoane5809
    @tiisetsontsoane5809 4 місяці тому

    How i wish there was a monthly subscription for the mastercourse class

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      The All Access Pass includes the Mastercourse.

  • @juliankohler5086
    @juliankohler5086 4 місяці тому

    What about Dependency Injection Singletons that implement IAsyncDisposable (or even IDisposable too)?

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +1

      If you are implementing a class that is registered in dependency injection as a singleton, dependency injection will handle the dispose calls when the application closes. Note that you need to think if you should be holding resources open that long, but that's an implementation detail.

    • @juliankohler5086
      @juliankohler5086 4 місяці тому

      @@IAmTimCorey It's possible that this is true even for a console app in C#, but I found the hard way that at least under certain circumstances, if you don't explicitly call Dispose on the container in F#, the garbage collector handles all the managed stuff normally, but if you have a more intricate task (like flushing a message queue, sending a last API request, something like that), it does not do it. Took me a while to realize it too. I had been dealing with the issue for 3 days before I asked you that. I'm not saying this is default behavior, I had a set of unique circumstances going on. So, to be safe, I would advise people to find the correct finally block to put their call to DisposeAsync (or Dispose, or both) on the DI container, just in case.

  • @tabhorian
    @tabhorian 4 місяці тому

    yeah, but how do you write a proper disposing? There are templates that intellisense shows you, but I'm never really too sure of what I have to keep track of and what is automatically kept track of. So in the end, I'm never really sure if I'm disposing of everything right, or being redundant. A second video on this would be really helpful to me

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @S3Kglitches
    @S3Kglitches 4 місяці тому +1

    Why isnt it available in MAUI xD (issue 7354)

  • @dyakobaram
    @dyakobaram 4 місяці тому

    can you make a video about the state of mobile development using c#? is it dead? should devs give it a try? or we should move on?

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @dsx7517
    @dsx7517 4 місяці тому

    What if I wanted to keep my database connection stored as a STATIC property in a class? I guess that would never get disposed automatically.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      Correct. And that would be a bad thing. Don't leave your connection open. Open it just long enough to get the data and then close it. That is super-efficient and it will reduce the overall load on your database server.

  • @yassinektata1804
    @yassinektata1804 2 місяці тому

    Because they both start with USING. And yes that's confUSING. (6:16)

  • @chidii
    @chidii 4 місяці тому

    What happens when we use the using statement without the IDisposable interface implemented

    • @simon-white
      @simon-white 4 місяці тому

      Try it 🙂 I would expect a compile time error - intellisense - saying it won't work, because it would try to execute a method that isn't guaranteed to exist.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +1

      It won't work. It relies on the class implementing that interface. If you try to use it that way, you will get a compile-time error and your code will not build.

  • @gower1973
    @gower1973 4 місяці тому

    Yeh but you can just close the connection in the catch block right?, this just seems like another abstraction, youve still got to implement the dispose function to actually clear up the mess!

    • @HolyRamanRajya
      @HolyRamanRajya 4 місяці тому +2

      Using=/=Exception Handling. One is a block of code to free resources, another is a runtime conditional logic tree for handling foreseen/unforeseen deviations to a defined rule/function, aka exceptions.
      In that old approach you would close connection on finally block not catch. And you need to know and implement the code needed to dispose said object. Using literally helps in re-usability. Using is not just for connections, it's for when interacting with unmanaged resources or non-deterministic systems.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +2

      The Dispose method allows you to properly shut things down. If you try to use the finally block, you have to rely on the caller to know how to properly release the resources. Also to do the proper checks to see if the connection is already closed, etc. This is a standard way to shut things down properly that doesn’t rely on the caller writing a lot of code each time.
      Also, there are things that you probably won’t expose publicly that need to be closed properly.

    • @Satanski666
      @Satanski666 4 місяці тому

      @@IAmTimCorey If i wrap "open connection - do stuff" block in try/catch and close connection in "finally", should i still implement IDisposable?

    • @holger_p
      @holger_p 4 місяці тому

      A using is the same thing as try/finally, just syntactic sugar, the Dispose is called in the finally-section. The exception will not break the using or the call to Dispose. You only catch it, if you want to do a special handling, log the error, things like that. You don't necessarily need to close the ressource in the catch, cause it's done at end of 'using' anyway. But sometimes you want to do a rollback/cleanup whatever.

    • @Satanski666
      @Satanski666 4 місяці тому

      @@holger_p Yeah, i know, i was was wondering if it makes sense to implement IDIsposable in DemoResource along doing try/catch/finally in DoWork method.

  • @DDDD-rr6uo
    @DDDD-rr6uo 4 місяці тому

    I really love your lessons Tim you are absolutely Jesus of c# for mostly people, but WHY you never use real world UI like one of your webbsite to let people se what you mean because sometimes you explain many important things with words and never have a summarize in the end...I mean many people are visualizer and want to se what this and that does in the website for instead

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +1

      This has nothing to do with a website or a specific UI. I showed you how it works. Not all code is going to be directly tied to a UI.

  • @Esgarpen
    @Esgarpen 4 місяці тому

    *General Grievous Voice*
    _Ah, another fine tool to add to my collection..._

  • @Sp1tfire100
    @Sp1tfire100 4 місяці тому

    Which vs theme is that?

    • @mibbio2148
      @mibbio2148 4 місяці тому +1

      Looks like the default dark theme except the yellow tabs, which might be a custom setting.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому

      It is just the standard Dark theme in Visual Studio. I don't have any special plug-ins or add-ons for color, etc. installed. I have enabled a few options from the Tools -> Options dialog that add some features. For example, my tab colors are from an option in Environment -> Tabs and Windows called "Colorize document tabs by:" and I chose "Project".

  • @dsx7517
    @dsx7517 4 місяці тому

    using is conf-using 😅

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +1

      Hopefully, this cleared it up.

  • @chezchezchezchez
    @chezchezchezchez 4 місяці тому +1

    Unsubscribed. it’s been a great few years, Tim, but I moved on to IOS

    • @SzalonyEdek
      @SzalonyEdek 4 місяці тому +5

      Is it a Tim’s fault?

    • @Bourn77
      @Bourn77 4 місяці тому +3

      My sympathies, for having to move from a great language like C# to that wall garnded cringe that is Swift 😂

    • @SKIDDOW
      @SKIDDOW 4 місяці тому +3

      iOS is not an independent OS for developers. Even we cannot run our-own app on our-own iOS device without paying to Apple. That means our Apple device is not ours even we have paid for it. It is a property of Apple Inc.

    • @IAmTimCorey
      @IAmTimCorey  4 місяці тому +3

      I hope you have great success in it.

    • @trustingod0
      @trustingod0 4 місяці тому

      Just because you got a job using iOS doesn’t make it better.