简体   繁体   中英

ViewBag Memory Leaks

I have a function that creates a list of objects and return it to be stored in the ViewBag.

The code will look like:

List<XDocument> xDocs = readXmlFiles(path);// a "new List<XDocument>()" is called
ViewBag.data = xDocs;
return View();

My question is, if we have the code as this, will the garbage collector release the allocated resources for the xDocs or not? or at least will it be freed once a new request for the same view is processed?

My question is, if we have the code as this, will the garbage collector release the allocated resources for the xDocs or not?

Yes, it will release it. The ViewBag will be eligible for garbage collection as soon as the request has finished executing.

or at least will it be freed once a new request for the same view is processed?

The exact timing of when the garbage collection occurs is out of your control. The CLR will choose the best suitable moment to perform it. This could happen before or after the next request. Since you are creating a new collection for each request this collection will be eligible for garbage collection once there are no longer any references to it (ie once the request has finished executing).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM