In my ASP.NET MVC action method to process uploaded files, I have
[HttpPost]
public async Task<ActionResult> UploadFiles(IEnumerable<IFormFile> files)
...
foreach (var file in files)
{
await using var stream = file.OpenReadStream();
...
Normal processing should mean that every file’s stream is disposed (as per the using).
But what happens if there is an exit from the loop before all files are processed – will ASP.NET dispose of all the other streams?
3
Answers
Sure
GarbageCollector
will take care of it. It’s good to manually dispose it, butGarbageCollector
is able to detect those variables which are not usable anymore.GarbageCollector
runs periodically, you can run it manually but it doesn’t occurs right after the loop, it happens at it’s period.see this question: Is a memory leak created if a MemoryStream in .NET is not closed?
ASP.NET manages the lifetime of whatever resources are used by
IFormFile
, not you. The only thing you have to worry about disposing is whateverOpenReadStream()
returns, and that’s taken care of by theusing
in your sample code. If your method throws an exception, then the runtime will clean that up for you.In general, if something isn’t disposable, don’t think about it.
ASP.NET supports uploading one or more files using buffered model binding for smaller files and unbuffered streaming for larger files.
The
disk
andmemory
used by file uploads depend on the number and size of concurrent file uploads. If an app attempts to buffer too many uploads, the site crashes when it runs out of memory or disk space.Any single buffered file exceeding
64 KB
is moved from memory to a temp file on disk.Temporary files for larger requests are written to the location named in the ASPNETCORE_TEMP environment variable. If ASPNETCORE_TEMP is not defined, the files are written to the current user’s temporary folder.
So it depends on the number and file sizes, if they are buffered in the memory they will clean after the request is finished (something like request scoped) if they are saved into a temp path then they will be removed by OS.
For more detail check this link: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-7.0