How IDisposable and Using Statements Work Together in C#

Sdílet
Vložit
  • čas přidán 4. 02. 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/

Komentáře • 134

  • @danielrubio3386
    @danielrubio3386 Před 4 měsíci +14

    Love these short and to the point videos.

    • @IAmTimCorey
      @IAmTimCorey  Před 4 měsíci +1

      Glad you like them!

    • @WyldStallion-bs9oo
      @WyldStallion-bs9oo Před měsícem

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

  • @abo1428
    @abo1428 Před 4 měsíci +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!

  • @00oKMo00
    @00oKMo00 Před 4 měsíci

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

  • @randyriegel8553
    @randyriegel8553 Před 4 měsíci +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  Před 4 měsíci +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.

  • @cyberbru1
    @cyberbru1 Před 4 měsíci

    Love this short videos Tim! Thank you for your content

  • @BigyanChap
    @BigyanChap Před 3 měsíci

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

  • @millstj
    @millstj Před 4 měsíci

    Wonderfully explained. Thanks Tim!

  • @felixmelendez6255
    @felixmelendez6255 Před 4 měsíci

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

  • @microtech2448
    @microtech2448 Před 4 měsíci +3

    Beautifully explained

  • @christopherlebron6912
    @christopherlebron6912 Před 4 měsíci

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

  • @krisztianlun3463
    @krisztianlun3463 Před 4 měsíci

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

  • @user-ew4wv9qb1g
    @user-ew4wv9qb1g Před 4 měsíci

    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!

  • @nandareddy4831
    @nandareddy4831 Před 4 měsíci

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

  • @JahirulIslam-le6ux
    @JahirulIslam-le6ux Před 3 měsíci

    Excellent tutorial and many many thanks

  • @tinker7722
    @tinker7722 Před 4 měsíci

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

  • @nickysmusic4592
    @nickysmusic4592 Před 4 měsíci

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

  • @MarioStaats
    @MarioStaats Před 4 měsíci

    Great information and brilliant explained. *thumbsUp

  • @MZZenyl
    @MZZenyl Před 4 měsíci +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.

  • @thegirigat
    @thegirigat Před 4 měsíci

    Very useful information, thank you

  • @AthanSousouris
    @AthanSousouris Před 4 měsíci

    Great video!

  • @BrentHollett
    @BrentHollett Před 3 měsíci

    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.

  • @salvatoreamaddio2983
    @salvatoreamaddio2983 Před 4 měsíci

    Thank you!

  • @gopikrishnag41
    @gopikrishnag41 Před 4 měsíci

    Nice informative video, thx

  • @handypda
    @handypda Před 4 měsíci

    Cheers Tim

  • @alexisgomez1198
    @alexisgomez1198 Před 2 měsíci

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

    • @IAmTimCorey
      @IAmTimCorey  Před 2 měsíci

      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

  • @georgestavrou8785
    @georgestavrou8785 Před 4 měsíci

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

    • @IAmTimCorey
      @IAmTimCorey  Před 4 měsíci +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.

  • @Max_Jacoby
    @Max_Jacoby Před 4 měsíci

    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?

  • @guilhermealves577
    @guilhermealves577 Před 2 dny

    Perfect!!

  • @robertlaszlo6074
    @robertlaszlo6074 Před 4 měsíci

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

    • @IAmTimCorey
      @IAmTimCorey  Před 4 měsíci

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

  • @199772AVVI
    @199772AVVI Před 4 měsíci +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  Před 4 měsíci +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?

  • @DavidMartin-vs1dm
    @DavidMartin-vs1dm Před 4 měsíci

    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  Před 4 měsíci +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.

  • @wagdyusrey7863
    @wagdyusrey7863 Před 4 měsíci

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

    • @IAmTimCorey
      @IAmTimCorey  Před 3 měsíci

      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/

  • @AhmadElkhouly
    @AhmadElkhouly Před 4 měsíci

    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  Před 4 měsíci

      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 Před 4 měsíci

    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 Před 4 měsíci

      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  Před 4 měsíci +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.

  • @S3Kglitches
    @S3Kglitches Před 4 měsíci +1

    Why isnt it available in MAUI xD (issue 7354)

  • @abhigupta3193
    @abhigupta3193 Před 4 měsíci

    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  Před 4 měsíci

      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/

  • @deniskarpenko4808
    @deniskarpenko4808 Před 4 měsíci

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

    • @IAmTimCorey
      @IAmTimCorey  Před 4 měsíci

      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/

  • @jasonrichmeier32
    @jasonrichmeier32 Před 4 měsíci

    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  Před 4 měsíci +1

      Well, hopefully more will know about it now.

  • @Lehnargh
    @Lehnargh Před 2 měsíci

    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  Před 2 měsíci

      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

  • @juliankohler5086
    @juliankohler5086 Před 3 měsíci

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

    • @IAmTimCorey
      @IAmTimCorey  Před 3 měsíci +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 Před 3 měsíci

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

  •  Před 4 měsíci +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 Před 4 měsíci +1

      good question 👍

    • @199772AVVI
      @199772AVVI Před 4 měsíci +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 Před 4 měsíci +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.

  • @dyakobaram
    @dyakobaram Před 4 měsíci

    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  Před 4 měsíci

      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/

  • @tabhorian
    @tabhorian Před 4 měsíci

    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  Před 3 měsíci

      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/

  • @holger_p
    @holger_p Před 4 měsíci

    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  Před 4 měsíci +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 Před 4 měsíci

      @@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  Před 4 měsíci

      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.

  • @dsx7517
    @dsx7517 Před 4 měsíci

    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  Před 4 měsíci

      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.

  • @tiisetsontsoane5809
    @tiisetsontsoane5809 Před 4 měsíci

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

    • @IAmTimCorey
      @IAmTimCorey  Před 4 měsíci

      The All Access Pass includes the Mastercourse.

  • @yassinektata1804
    @yassinektata1804 Před měsícem

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

  • @chidii
    @chidii Před 4 měsíci

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

    • @simon-white
      @simon-white Před 4 měsíci

      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  Před 4 měsíci +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 Před 4 měsíci

    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 Před 4 měsíci +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  Před 4 měsíci +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 Před 4 měsíci

      @@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 Před 4 měsíci

      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 Před 4 měsíci

      @@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 Před 4 měsíci

    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  Před 4 měsíci +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 Před 4 měsíci

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

  • @Sp1tfire100
    @Sp1tfire100 Před 4 měsíci

    Which vs theme is that?

    • @mibbio2148
      @mibbio2148 Před 4 měsíci +1

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

    • @IAmTimCorey
      @IAmTimCorey  Před 4 měsíci

      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 Před 4 měsíci

    using is conf-using 😅

  • @chezchezchezchez
    @chezchezchezchez Před 4 měsíci +1

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

    • @SzalonyEdek
      @SzalonyEdek Před 4 měsíci +5

      Is it a Tim’s fault?

    • @Bourn77
      @Bourn77 Před 4 měsíci +3

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

    • @SKIDDOW
      @SKIDDOW Před 4 měsíci +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  Před 4 měsíci +3

      I hope you have great success in it.

    • @trustingod0
      @trustingod0 Před 4 měsíci

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