Friday 31 October 2014

Memory leak in CS

A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system. In object-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code. 

A memory leak can diminish the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down unacceptably due to thrashing.

There are many ways to avoid memory leak in C#; we can avoid memory leak while working with unmanaged resources with the help of the ‘using’ statement, which internally calls Dispose() method. The syntax for the ‘using’ statement is as follows:

using(var  objectName = new AnyDisposableType)
{
  //user code
}

There are two major causes for memory leak in C#:

  1. The first cause is having an unused object that is no longer required but still referenced by a variable that has its scope throughout the application’s lifetime. Since this object has a reference, it will not be destroyed by the garbage collector and will remain in the memory forever and can become a reason for a memory leak. An example of this situation can be an event that we have registered but is never unregistered.
  2. The second cause is allocating the memory for unmanaged resources and then not releasing it after use. Whenever we are working with objects that are not collected by the garbage collector, we need to be extra careful to dispose of them after use. Otherwise, these will cause a memory leak as they are not cleaned up by the GC.
Conclusion
When an application doesn’t release the memory that it has used during its execution, this memory will be blocked and cannot be used by any other process, resulting in a memory leak. The garbage collector can automatically dispose of managed objects but cannot dispose of unmanaged objects or resources.


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives