How to clear a memory early in c#

40,259

Solution 1

If there are specific resources that need to be released immediately, implement the IDisposable interface and call Dispose() (sometimes Close() on some objects, such as streams).

If you are looking to prevent passwords being retained in memory beyond their lifespan, SecureString supports this, though it is not simple to use.

Otherwise, you have no control over when the garbage collector runs or what it actually does. If you desperately need this kind of control, you need a lower level language.

Solution 2

As @Hinek said, you should call GC.Collect(). However, it alone won't do the part if you want the memory to be cleared immediately. You should call :

   //Force garbage collection.
   GC.Collect();

   // Wait for all finalizers to complete before continuing.
   GC.WaitForPendingFinalizers();

Solution 3

Set it's value to null. Than GC will collect it(during next GC run), if no other references to this object found. But you cannot clear memory by your own (except for unmanaged resources).

Solution 4

you can use this method:

public static void FlushMemory()
    {
        Process prs = Process.GetCurrentProcess();
        try
        {
            prs.MinWorkingSet = (IntPtr)(300000);
        }
        catch (Exception exception)
        {
            throw new Exception();
        }
    }

three way to use this method.

1 - after dispose managed object such as class ,....

2 - create timer with such 2000 intervals.

3 - create thread to call this method.

i suggest to you use this method in thread or timer.

Solution 5

As @Mayank said use both

GC.Collect();
GC.WaitForPendingFinalizers();

Since the program will not continue and increase memory usage until free the previous used memory.

Share:
40,259
user496949
Author by

user496949

Updated on February 19, 2020

Comments

  • user496949
    user496949 about 4 years

    After finishing use the varible, can I clear the memory early before the GC do it?