I am a newer to C#. Recently when I update an application(vs2008), I met the following problem.
The application has c++ function helper as follows:
array<float>^ Variant::CopyToFloats()
{
unsigned int n = this->data_uint8->Length;
array<float>^ dst = gcnew array<float>(n); //<<OutOfMemoryException happened here
for (unsigned int i = 0; i < n; i++)
dst[i] = (float)this->data_uint8[i];
return dst;
}
In c# file,
for(int i=0; i<m; i++)
{ for(int j=0; j<n; j++)
{
float[] scan = data[i].CopyToFloats();
for(int k=0; k<nn; k++)
sample[k]=scan[function(i,j)];
}
}
When I run the application, OutOfMemoryException happens.
Then I added the following code
Process proc = Process.GetCurrentProcess();
long memory = proc.PrivateMemorySize64;
before and after the outer loop, I found that the memory of scan was not released.
I tried the following ways:
1.Clear scan and set it to null, with/without using GC.Collect()
for(int i=0; i<m; i++)
{ for(int j=0; j<n; j++)
{
float[] scan = data[i].CopyToFloats();
for(int k=0; k<nn; k++)
sample[k]=scan[function(i,j)];
}
Array.Clear(scan, 0, scan.Length);
scan = null;
//GC.Collect();
}
With calling GC.Collect(), the program ran very slowly. Without calling, the program still crashed as OOME.
I was wondering which memory is not released? scan or array created by gcnew?
2.As the array size is big(>500000), I allocate big size array before entering the loop.
float[] scan = new float[data[0].GetSize()];
for(int i=0; i<m; i++)
{ for(int j=0; j<n; j++)
{
scan = data[i].CopyToFloats();
for(int k=0; k<nn; k++)
sample[k]=scan[function(i,j)];
}
}
But OOME still happened. From here, I am kind of sure that the memory of array created by gcnew was not released. Am I right? If I am right, why it was not released? Is there any way to release this memory? If I am not right, please give me some advice, thanks!