0

We are currently using .net DLLs which are made from MATLAB and We are sending byte Array from C# to Method in this DLL. Each time we call, we are creating byte array of 6MB. Is there is any way to clear this array when the function returns?

We already tested with GC.Collect() but no luck.

Thanks in Advance.

4
  • Why would you call GC.Collect on your array? Collecting it is not what you want to do here. Commented Mar 25, 2014 at 10:26
  • Do you want to clear the memory just to reset the values, and re-use the array, or do you want to remove it to free up more memory? Commented Mar 25, 2014 at 10:34
  • @Kjartan, I would like clear it to free up memory used Commented Mar 25, 2014 at 10:35
  • That's what I thought. You just have to make sure the reference is removed then (see my answer below). Commented Mar 25, 2014 at 10:39

3 Answers 3

5

you can use Array.Clear to clear out the array. For example

Array.Clear(YourByteArray,0,YourByteArray.Length);
Sign up to request clarification or add additional context in comments.

2 Comments

This will only clear the values, any possible to free up memory?
let the framework take care of it. all you need to do is to don't keep a reference to your array. it will be freed as soon as framework deems necessary.
2

Clearing out the array can be done with Array.Clear, but that will not release memory as long as there is a reference to the array; since an array has a constant size, it's content is not really relevant.

What you need to do is ensure there are no references to it left. Only after that will the garbage collector handle it and free the memory (although there is no guarantee as to exactly when that will happen).

This can happen automatically when the relevant array variable is no longer in scope, and there is nothing else referring to it. If you need to "remove" it manually, you can achieve this by setting the variable to null. That is probably (?) the quickest way to enable the GC to discover that there is something to be collected here...

Comments

1

First you clear your array by using Array.Clear and then de-reference the array using yourArray = null, and the re-declare it

2 Comments

Sets a range of elements in the Array to zero, to false, or to null (Nothing in Visual Basic), depending on the element type.
I realize that, but if you don't need that array again, that just seems to me like O(n) extra, unnecessary operations.. No big deal, just no point either, if I'm not mistaken..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.