Home News Fix: How To Fix Memory Leak In C # .net

Fix: How To Fix Memory Leak In C # .net

79
0

 

Here are some simple steps you can follow to fix memory leak in C # .net.

A memory leak occurs when an application is unable to free that memory, preventing it from being reallocated. In managed code, the garbage collector keeps track of object references created by the application. 17 February 2011

 

 

When an application is allocated memory, it must return that memory to the operating system so that it can be reused by other applications. A memory leak occurs when an application is unable to free that memory, preventing it from being reallocated.

In managed code, the garbage collector keeps track of object references created by the application. In most cases, the CLR will transparently and appropriately handle allocating and freeing memory on behalf of the current process. However, .NET developers should always consider resource management, as there are still situations where memory can be lost despite the garbage collector.

Consider the following code:

what is memory leak in c#.net

Widget widget = new widget ();

The line of code above creates a new instance of the Widget class and assigns a reference to that object to the widget field. The GC keeps track of the references associated with each object and frees memory of objects that do not have strong references.

Note that CLR garbage collection only collects managed objects. .NET code can and often does notObtainable resources that cannot be collected automatically.

Unmanaged resource leaks occur when the object for which these resources have been allocated is not properly released before the last reference to those resources is out of range. Thus, there are no references to the assigned resources and therefore the application cannot use them.

Classes that directly reference unmanaged resources must ensure that those resources are properly deallocated. An example of this might look like this:

  public void ManagedObject: IDisposable{    // Handle to your own resource.    int * handle;    public ManagedObject ()    {        // AllocateHandle is a native method called via P / Invoke.        handle = AllocateHandle ();    }}    public void Dispose ()    {        Eliminate (true);        GC.SuppressFinalize (this);    }}    private void Dispose (removing boolean values)    {        if (exclude)        {            // process the resources managed here            FreeHandle (handle);        }}    }}    ~ ManagedType ()    {        Eliminate (incorrect);    }}}} 

destroy is false if called by a finalizer. itThis is to prevent the use of managed resources in the finalizer, since managed references should be considered invalid at this stage.

Notice also that the Dispose () method calls GC.SuppressFinalize (this) , which prevents the finalizer from running on this instance. This is because the resources that would have been freed in the finalizer were freed in the call to Dispose, so there is no need to call Fializer.

Client code that uses classes that deal with unmanaged resources (or any class that implements IDisposable) must do so in a using block to ensure that IDisposable .Dispose < / code> is called when access to the resource is no longer needed because it handles both managed and unmanaged resources, and in the example above, it ensures that the finalizer is not called very expensively.

Congratulations on your trip. I will stop now.

What Type Of Memory Leak? Shared Memory = Managed Memory Unmanaged Memory

Before trying to understand the nature of the leak, let's askLet's understand how memory is allocated in .NET applications. .NET applications have two types of managed memory and unmanaged memory. Managed memory is controlled by the garbage collector, and unmanaged memory is outside the limits of the garbage collector.

The first thing we need to do to make sure there is a memory leak is a managed or unhandled leak. To determine if the leak has been repaired, two performance counters must be measured.

The first is the application's private byte counter that we saw in the previous session.
The second counter we need to add is bytes in all heaps. So select ".NET CLR memory" in the performance object, select "Bytes in All Heaps" in the list of counters, and select the application that is losing memory.


Private bytes are all memory used by the application. The bytes of all heaps are the memory used by the managed code. Thus, the equation takes the form shown in the following figure.

Unmanaged memory bytes in all helpers = private bytes. Therefore, if we want to find notmanaged memory, we can always subtract the bytes of all heaps from the private bytes.

We will now make two statements:

  • If the private bytes are incremented and the bytes in all heaps remain constant, this means an unhandled memory leak.

  • If the bytes of all heaps grow linearly, this means that this is a controlled memory leak.

Here is a typical screen shot of a raw leak. You can see the private bytes are incremented and the bytes in the heaps remain constant

Here is a typical screen shot of a managed leak. Bytes of all heaps are incremented.

2. Registration Of Participants Using Anonymous Methods

While it may be obvious that an event-handling method means that an object is being referenced, it is less obvious that the same is true when a class member is captured by an anonymous method.

Here's an example:

In this code, the _id member is registered with the anonymous method, and the instance is also referenced accordingly. This means that JobQueue exists and refers to this worker delegate, but also refers to the MyClass instance.

The solution can be quite simple: assign a local variable:

By assigning a value to a local variable, nothing is saved and you avoid a possible memory leak.

 

 

What can cause memory leak?

A memory leak occurs when references to objects that are no longer needed are kept unnecessarily. These leaks are bad. On the one hand, they put unnecessary strain on your computer as your programs consume more and more resources.

How detect memory leak in .NET application?