The Usage key helps you do something that needs to be done safely and clearly in .net. This property is the placement of certain objects. You may have learned how we have garbage collection in .Net, which means that for many objects we do not need to take care of them when we have finished using them. However, for another object, a method called Dispose must be called. Best practice is that whenever an object has a Dispose method, we must call this method when we are done with this object.
(They typically handle unmanaged resources . This means that it uses memory or other parts of the computer that are outside of the control of the .NET runtime. Therefore, when garbage collection reaches a dropped .Net object, it cannot efficiently release these resources. which may cause a memory leak and all other problems. A good example is ADO.NET Connection repeatedly. Removing your connection objects may cause database problems.)
Using key is also tied to this "Dispose" method. More precisely, when an object has a Dispose method, we either call ( A. ). Ask when we are done with it, or ( B ). put our code that uses this object in the Usage block. The Usage block does a few things for you:
- When the code exits the block, the important Dispose method is automatically called for you.
- More importantly, if there is an error in the code block, the Dispose method will still be called. This is why the use block is really useful. Otherwise, you will have to add a lot of error handling code.
The key is that for many of these objects that have a Dispose method, error handling is especially high . For our code, we do not need error handling; The consequences of the error occurring are not really a problem. But for these IDisposable objects, errors are often a problem, maybe a big problem. As such, .Net provides syntax for busy developers to add the most basic error handling and move on. Always start with at least the Use block; you may later move on to more convenient error handling, but at least you have this basic security.
Here is a good explanation of the Using keyword .
source share