CSharp – Memory leaks problem detection and solution

/* By Dylan SUN*/

Out of memory exception happens when server doesn’t have enough memory to run the application.

This often happens when you are dealing with external resources, such as consuming Interop libraries, treating files, streams, etc.

Memory is a limited resource, it’s easy to be run out of. So, you should be careful when you are working with external resources in your application development.

There are some good memory profilers in the market.
I’ve listed two profilers I’ve used. They are both very easy to use. You can even try them for a limited period.

  1. DotTrace
  2. Ants Memory Profiler

Here are some screenshots of one snapshot in Ants memory profiler.

You could see the memory usage progress with time.
progress

You could easily see the memory usage with Heap generation 1, generation 2, Large object heap, Unused memory allocated to .NET, Unmanaged memories.

这里写图片描述

Then you could investigate which instance of class is used, how much times it’s been used, how many memory it has occupied, etc.

这里写图片描述

The best practice to consume an external data source is using “using” statement. Everything you get in external services will be disposed.

using (var service = _serviceAdapter.Configure())
{
var data = _serviceAdapter.RetrieveData(parameters);
}

If you need to use the retrieved data in several places in your application. You can convert it to a DTO object, so the code becomes managed.

DataDto dataDto = new DataDto();
using (var service = _serviceAdapter.Configure())
{
var data = _serviceAdapter.RetrieveData(parameters);
dtoData = ConvertToDto(data);
}

In this way you can use dtoData wherever you like.
After the object’s usage, the data will be collected by GC later.

You can translate the previous code into :

Service service = new Service();
Data data = new Data();
try
{
service = _serviceAdapter.Configure();
data = _serviceAdapter.RetrieveData(parameters);
dtoData = ConvertToDto(data);
}
finally
{
service.Dispose();
data.Dispose();
}

If you want to ensure that all exceptions will be caught. You can do something like this:

Service service = new Service();
Data data = new Data();
try
{
service = _serviceAdapter.Configure();
data = _serviceAdapter.RetrieveData(parameters);
dtoData = ConvertToDto(data);
}
catch(Exception ex)
{
Logger.LogError(ex.Message + ex.StackTrace);
}
finally
{
service.Dispose();
data.Dispose();
}

I hope you find this articles helpful!

波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 本站源码并不保证全部能正常使用,仅供有技术基础的人学习研究,请谨慎下载
8. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » CSharp – Memory leaks problem detection and solution
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡