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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值