1. If the garbage collector immediately takes away the memory?
The garbage collector does not free up memory right away because it is a laborious operation. When garbage collection occurs, all threads controlled by your application are suspended. This results in an unwanted delay. Thus, the garbage collector acts only occasionally, based on a complex algorithm.
2. In all disposable objects, I use the syntax "using", but this does not help.
The using statement refers to unmanaged resources that are in limited numbers (typically associated with IOs, such as file descriptors, databases, and network connections). Therefore, this statement does not affect garbage collection.
3. Am I missing something?
It doesn't seem like you need the original byte array after you wrapped it with ByteArrayContent . You do not clear model.File after packing it, and the array can be passed to the Index view.
I would replace:
using(var binaryReader = new BinaryReader(file.InputStream)) { model.File = binaryReader.ReadBytes(file.ContentLength); } var fileContent = new ByteArrayContent(model.File);
from:
ByteArrayContent fileContent = null; using(var binaryReader = new BinaryReader(file.InputStream)) { fileContent = new ByteArrayContent(binaryReader.ReadBytes(file.ContentLength)); }
to avoid the need for a clean model.File .
4. If I continue to download files, the memory simply increases until the server is completely lowered.
If your files average 80 MB, they fall into a bunch of large objects. The heap does not compact automatically and usually does not collect garbage. It looks like in your case a large heap of an object grows infinitely (which can happen).
If you use (or can upgrade to) .NET 4.5.1 or later, you can force a large heap of the object to be compressed by setting:
System.Runtime.GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
You will need to call this line of code every time you want to schedule the heap compaction of a large object in the next complete garbage collection.
You can also force compression by calling:
System.Runtime.GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; System.GC.Collect();
However, if you need to free up a lot of memory, this will be a costly operation in terms of time.